Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 package org.apache.sling.engine.impl.log;
 
 
 import  org.osgi.framework.BundleContext;

The RequestLogger is a request level filter, which provides customizable logging or requests handled by Sling. This filter is inserted as the first filter in the request level filter chain and therefore is the first filter called when processing a request and the last filter acting just before the request handling terminates.
 
 @Component(immediate=true,metatype=true,label="%request.log.name",description="%request.log.description")
     @Property(name="service.description",value="Request Logger"),
     @Property(name="service.vendor",value="The Apache Software Foundation")
 })
 @Service(value=RequestLogger.class)
 @Reference(name="RequestLoggerService",
        referenceInterface=RequestLoggerService.class,
        cardinality=.,
        policy=.)
 public class RequestLogger {
 
     @Property(value="logs/request.log")
     public static final String PROP_REQUEST_LOG_OUTPUT = "request.log.output";
 
     @Property(intValue=0,options={
             @PropertyOption(name = "0", value = "Logger Name"),
             @PropertyOption(name = "1", value = "File Name"),
             @PropertyOption(name = "2", value = "RequestLog Service")
     })
     public static final String PROP_REQUEST_LOG_OUTPUT_TYPE = "request.log.outputtype";
 
     @Property(boolValue=true)
     public static final String PROP_REQUEST_LOG_ENABLED = "request.log.enabled";
 
     @Property(value="logs/access.log")
     public static final String PROP_ACCESS_LOG_OUTPUT = "access.log.output";
 
     @Property(intValue=0,options={
             @PropertyOption(name = "0", value = "Logger Name"),
             @PropertyOption(name = "1", value = "File Name"),
             @PropertyOption(name = "2", value = "RequestLog Service")
     })
     public static final String PROP_ACCESS_LOG_OUTPUT_TYPE = "access.log.outputtype";
 
     @Property(boolValue=true)
     public static final String PROP_ACCESS_LOG_ENABLED = "access.log.enabled";

    
The log format string for the request log entry message (value is "%t [%R] -> %m %U%q %H").
 
     private static final String REQUEST_LOG_ENTRY_FORMAT = "%t [%R] -> %m %U%q %H";

    
The log format string for the request log exit message (value is "%{end}t [%R] <- %s %{Content-Type}o %Dms").
 
     private static final String REQUEST_LOG_EXIT_FORMAT = "%{end}t [%R] <- %s %{Content-Type}o %Dms";

    
The log format for the access log which is exactly the NCSA extended/combined log format (value is "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"").
 
    private static final String ACCESS_LOG_FORMAT = "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"";

    
The list of RequestLoggerService called when the request enters processing. The order of the services in this list determined by the registration order.
    private RequestLoggerService[] requestEntry;

    
The list of RequestLoggerService called when the request is about to exit processing. The order of the services in this list determined by the registration order.
    private RequestLoggerService[] requestExit;

    
A special request logger service, which writes the request log message at request start time. This logger logs a message with the format REQUEST_LOG_ENTRY_FORMAT.
    private RequestLoggerService requestLogEntry;

    
A special request logger service, which writes the request log message at request termination time. This logger logs a message with the format REQUEST_LOG_EXIT_FORMAT.
    private RequestLoggerService requestLogExit;

    
A special request logger service, which writes the access log message at request termination time. This logger logs a message with the format NCSA extended/combined log format.
    public void logRequestEntry(SlingHttpServletRequest requestSlingHttpServletResponse response) {
        if (response instanceof SlingHttpServletResponseImpl) {
            // log the request start
            if (this. != null) {
                for (int i = 0; i < this..lengthi++) {
                    this.[i].log(request,
                        (SlingHttpServletResponseImplresponse);
                }
            }
        }
    }
    public void logRequestExit(SlingHttpServletRequest requestSlingHttpServletResponse response) {
        // signal the end of the request
        if (response instanceof SlingHttpServletResponseImpl) {
            SlingHttpServletResponseImpl loggerResponse = (SlingHttpServletResponseImplresponse;
            loggerResponse.requestEnd();
            // log the request end
            if (this. != null) {
                for (int i = 0; i < this..lengthi++) {
                    this.[i].log(requestloggerResponse);
                }
            }
        }
    }
    // ---------- SCR Integration ----------------------------------------------

    
Activates this component by setting up the special request entry and exit request loggers and the access logger as configured in the context properties. In addition the FileRequestLog class is initialized with the value of the sling.home context property to resolve relative log file names.

Parameters:
osgiContext The OSGi Component Context providing the configuration data and access into the system.
    protected void activate(
            org.osgi.service.component.ComponentContext osgiContext) {
        BundleContext bundleContext = osgiContext.getBundleContext();
        @SuppressWarnings("unchecked")
        Dictionary props = osgiContext.getProperties();
        // initialize the FileRequestLog with sling.home as the root for
        // relative log file paths
        FileRequestLog.init(bundleContext.getProperty("sling.home"));
        // prepare the request loggers if a name is configured and the
        // request loggers are enabled
        Object requestLogName = props.get();
        Object requestLogEnabled = props.get();
        if (requestLogName != null && requestLogEnabled instanceof Boolean
            && ((BooleanrequestLogEnabled).booleanValue()) {
            Object requestLogType = props.get();
            this. = this.createRequestLoggerService(bundleContexttrue,
                requestLogNamerequestLogType);
            this. = this.createRequestLoggerService(bundleContextfalse,
                requestLogNamerequestLogType);
            this.bindRequestLoggerService(this.);
            this.bindRequestLoggerService(this.);
        }
        // prepare the access logger if a name is configured and the
        // access logger is enabled
        Object accessLogName = props.get();
        Object accessLogEnabled = props.get();
        if (accessLogName != null && accessLogEnabled instanceof Boolean
            && ((BooleanaccessLogEnabled).booleanValue()) {
            Object accessLogType = props.get();
            this. = this.createRequestLoggerService(bundleContextfalse,
                accessLogNameaccessLogType);
            this.bindRequestLoggerService(this.);
        }
    }

    
Deactivates this component by unbinding and shutting down all loggers setup during activation and finally dispose off the FileRequestLog class to make sure all shared writers are closed.

Parameters:
osgiContext The OSGi Component Context providing the configuration data and access into the system.
    protected void deactivate(
            org.osgi.service.component.ComponentContext osgiContext) {
        // remove the loggers if they have been set up
        if (this. != null) {
            this.unbindRequestLoggerService(this.);
            this..shutdown();
            this. = null;
        }
        if (this. != null) {
            this.unbindRequestLoggerService(this.);
            this..shutdown();
            this. = null;
        }
        if (this. != null) {
            this.unbindRequestLoggerService(this.);
            this..shutdown();
            this. = null;
        }
        // hack to ensure all log files are closed
        FileRequestLog.dispose();
    }

    
Binds a RequestLoggerService to be used during request filter.

Parameters:
requestLoggerService The RequestLoggerService to use.
    protected void bindRequestLoggerService(
            RequestLoggerService requestLoggerService) {
        if (requestLoggerService.isOnEntry()) {
            this. = this.addService(this.requestLoggerService);
        } else {
            this. = this.addService(this.requestLoggerService);
        }
    }

    
Binds a RequestLoggerService to be used during request filter.

Parameters:
requestLoggerService The RequestLoggerService to use.
    protected void unbindRequestLoggerService(
            RequestLoggerService requestLoggerService) {
        if (requestLoggerService.isOnEntry()) {
            this. = this.removeService(this.requestLoggerService);
        } else {
            this. = this.removeService(this.requestLoggerService);
        }
    }

    
Create a RequestLoggerService instance from the given configuration data. This method creates a Properties object from the data which may be handled by the RequestLoggerService.RequestLoggerService(BundleContext, Dictionary) constructor to set itself up.

Parameters:
bundleContext The BundleContext used to setup a ServiceTracker should the output be a RequestLog service.
onEntry Whether the logger is to be called on request entry (true) or not (false).
format The log format string. This is expected to be a String.
output The name of the output, which may be an SLF4J logger, a relative or absolute file name or the name of a RequestLog service. This is expected to be a String.
outputType The type of output, 0 for SLF4J logger, 1 for file name and 2 for a service name. This is expected to be an Integer.
Returns:
The functional and prepared RequestLoggerService instance.
            BundleContext bundleContextboolean onEntryObject format,
            Object outputObject outputType) {
        final Hashtable<StringObjectconfig = new Hashtable<StringObject>();
        config.put(.onEntry
                ? .
                : .);
        config.put(.format);
        config.put(.output);
        config.put(.outputType);
        return new RequestLoggerService(bundleContextconfig);
    }

    
Creates a new list of request logger services from the existing list appending the new logger. This method does not check, whether the logger has already been added or not and so may add the the logger multiple times. It is the responsibility of the caller to make sure to not add services multiple times.

Parameters:
list The list to add the new service to
requestLoggerService The service to append to the list
A new list with the added service at the end.
            RequestLoggerService requestLoggerService) {
        if (list == null) {
            return new RequestLoggerService[] { requestLoggerService };
        }
        // add the service to the list, must not be in the list yet due to
        // the SCR contract
        RequestLoggerService[] newList = new RequestLoggerService[list.length + 1];
        System.arraycopy(list, 0, newList, 0, list.length);
        newList[list.length] = requestLoggerService;
        return newList;
    }

    
Creates a new list of request logger services from the existing list by removing the named logger. The logger is searched for by referential equality (comparing the object references) and not calling the equals method. If the last element is being removed from the list, null is returned instead of an empty list.

Parameters:
list The list from which the service is to be removed.
requestLoggerService The service to remove.
Returns:
The list without the service. This may be the same list if the service is not in the list or may be null if the last service has just been removed from the list.
            RequestLoggerService requestLoggerService) {
        RequestLoggerService[] newList = null;
        for (int i = 0; list != null && i < list.lengthi++) {
            if (list[i] == requestLoggerService) {
                newList = new RequestLoggerService[list.length - 1];
                // if not first take over the leading elements
                if (i > 0) {
                    System.arraycopy(list, 0, newList, 0, i);
                }
                // if not the last element, shift rest to the left
                if (i < list.length - 1) {
                    System.arraycopy(listi + 1, newList, 0, newList.length
                        - i);
                }
            }
        }
        // return the new list if at least one entry is contained
        return (newList != null && newList.length > 0) ? newList : null;
    }
New to GrepCode? Check out our FAQ X