001/*
002 * (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.platform.ui.web.util;
020
021import javax.faces.view.facelets.Tag;
022
023import org.apache.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
025import org.nuxeo.runtime.api.Framework;
026import org.nuxeo.runtime.services.config.ConfigurationService;
027
028/**
029 * @since 8.2
030 */
031public class FaceletDebugTracer {
032
033    private static final Log log = LogFactory.getLog(FaceletDebugTracer.class);
034
035    public static final String TRACE_PROP = "nuxeo.jsf.debug.log_min_duration_ms";
036
037    public static long start() {
038        if (getMaxTraceLag() >= 0) {
039            return System.currentTimeMillis();
040        }
041        return 0;
042    }
043
044    public static void trace(long start, Tag tag, String id) {
045        if (start > 0) {
046            trace(start, tag, id, getMaxTraceLag());
047        }
048    }
049
050    public static void traceMillis(long start, Tag tag, String id) {
051        trace(start, tag, id, 0);
052    }
053
054    public static void trace(long start, Tag tag, String id, long maxLag) {
055        if (start > 0 && maxLag >= 0) {
056            long end = System.currentTimeMillis();
057            long lag = end - start;
058            if (lag >= maxLag) {
059                log.debug(String.format("'%s' at '%s' took: %s ms.", id, tag, lag));
060            }
061        }
062    }
063
064    protected static long getMaxTraceLag() {
065        if (log.isDebugEnabled()) {
066            ConfigurationService cs = Framework.getService(ConfigurationService.class);
067            return Long.valueOf(cs.getProperty(TRACE_PROP, "-1"));
068        }
069        return -1;
070    }
071
072}