"Fossies" - the Fresh Open Source Software Archive

Member "apache-log4j-2.12.4-src/src/site/xdoc/manual/eventlogging.xml" (20 Dec 2021, 6724 Bytes) of package /linux/misc/apache-log4j-2.12.4-src.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) XML source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

    1 <?xml version="1.0"?>
    2 <!--
    3     Licensed to the Apache Software Foundation (ASF) under one or more
    4     contributor license agreements.  See the NOTICE file distributed with
    5     this work for additional information regarding copyright ownership.
    6     The ASF licenses this file to You under the Apache License, Version 2.0
    7     (the "License"); you may not use this file except in compliance with
    8     the License.  You may obtain a copy of the License at
    9 
   10          http://www.apache.org/licenses/LICENSE-2.0
   11 
   12     Unless required by applicable law or agreed to in writing, software
   13     distributed under the License is distributed on an "AS IS" BASIS,
   14     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   15     See the License for the specific language governing permissions and
   16     limitations under the License.
   17 -->
   18 
   19 <document xmlns="http://maven.apache.org/XDOC/2.0"
   20           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   21           xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">
   22     <properties>
   23         <title>Log4j 2 API</title>
   24         <author email="rgoers@apache.org">Ralph Goers</author>
   25     </properties>
   26 
   27     <body>
   28         <section name="Log4j 2 API">
   29           <a name="EventLogging"/>
   30           <subsection name="Event Logging">
   31             <p>
   32               The EventLogger class provides a simple mechanism for logging events that occur in an application.
   33               While the EventLogger is useful as a way of initiating events that should be processed by an audit
   34               Logging system, by itself it does not implement any of the features an audit logging system would require
   35               such as guaranteed delivery.
   36             </p>
   37             <p>The recommended way of using the EventLogger in a typical web application is to populate
   38               the ThreadContext Map with data that is related to the entire lifespan of the request such as the user's
   39               id, the user's IP address, the product name, etc. This can easily be done in a servlet filter where
   40               the ThreadContext Map can also be cleared at the end of the request. When an event that needs to be
   41               recorded occurs a StructuredDataMessage should be created and populated.
   42               Then call EventLogger.logEvent(msg) where msg is a reference to the StructuredDataMessage.</p>
   43 
   44             <pre class="prettyprint linenums">
   45 import org.apache.logging.log4j.ThreadContext;
   46 import org.apache.commons.lang.time.DateUtils;
   47 
   48 import javax.servlet.Filter;
   49 import javax.servlet.FilterConfig;
   50 import javax.servlet.ServletException;
   51 import javax.servlet.ServletRequest;
   52 import javax.servlet.ServletResponse;
   53 import javax.servlet.FilterChain;
   54 import javax.servlet.http.HttpSession;
   55 import javax.servlet.http.HttpServletRequest;
   56 import javax.servlet.http.Cookie;
   57 import javax.servlet.http.HttpServletResponse;
   58 import java.io.IOException;
   59 import java.util.TimeZone;
   60 
   61 public class RequestFilter implements Filter {
   62     private FilterConfig filterConfig;
   63     private static String TZ_NAME = "timezoneOffset";
   64 
   65     public void init(FilterConfig filterConfig) throws ServletException {
   66         this.filterConfig = filterConfig;
   67     }
   68 
   69     /**
   70      * Sample filter that populates the MDC on every request.
   71      */
   72     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
   73             throws IOException, ServletException {
   74         HttpServletRequest request = (HttpServletRequest)servletRequest;
   75         HttpServletResponse response = (HttpServletResponse)servletResponse;
   76         ThreadContext.put("ipAddress", request.getRemoteAddr());
   77         HttpSession session = request.getSession(false);
   78         TimeZone timeZone = null;
   79         if (session != null) {
   80             // Something should set this after authentication completes
   81             String loginId = (String)session.getAttribute("LoginId");
   82             if (loginId != null) {
   83                 ThreadContext.put("loginId", loginId);
   84             }
   85             // This assumes there is some javascript on the user's page to create the cookie.
   86             if (session.getAttribute(TZ_NAME) == null) {
   87                 if (request.getCookies() != null) {
   88                     for (Cookie cookie : request.getCookies()) {
   89                         if (TZ_NAME.equals(cookie.getName())) {
   90                             int tzOffsetMinutes = Integer.parseInt(cookie.getValue());
   91                             timeZone = TimeZone.getTimeZone("GMT");
   92                             timeZone.setRawOffset((int)(tzOffsetMinutes * DateUtils.MILLIS_PER_MINUTE));
   93                             request.getSession().setAttribute(TZ_NAME, tzOffsetMinutes);
   94                             cookie.setMaxAge(0);
   95                             response.addCookie(cookie);
   96                         }
   97                     }
   98                 }
   99             }
  100         }
  101         ThreadContext.put("hostname", servletRequest.getServerName());
  102         ThreadContext.put("productName", filterConfig.getInitParameter("ProductName"));
  103         ThreadContext.put("locale", servletRequest.getLocale().getDisplayName());
  104         if (timeZone == null) {
  105             timeZone = TimeZone.getDefault();
  106         }
  107         ThreadContext.put("timezone", timeZone.getDisplayName());
  108         filterChain.doFilter(servletRequest, servletResponse);
  109         ThreadContext.clear();
  110     }
  111 
  112     public void destroy() {
  113     }
  114 }</pre>
  115             <p>Sample class that uses EventLogger.</p>
  116             <pre class="prettyprint linenums">
  117 import org.apache.logging.log4j.StructuredDataMessage;
  118 import org.apache.logging.log4j.EventLogger;
  119 
  120 import java.util.Date;
  121 import java.util.UUID;
  122 
  123 public class MyApp {
  124 
  125     public String doFundsTransfer(Account toAccount, Account fromAccount, long amount) {
  126         toAccount.deposit(amount);
  127         fromAccount.withdraw(amount);
  128         String confirm = UUID.randomUUID().toString();
  129         StructuredDataMessage msg = new StructuredDataMessage(confirm, null, "transfer");
  130         msg.put("toAccount", toAccount);
  131         msg.put("fromAccount", fromAccount);
  132         msg.put("amount", amount);
  133         EventLogger.logEvent(msg);
  134         return confirm;
  135     }
  136 }</pre>
  137             <p>The EventLogger class uses a Logger named "EventLogger". EventLogger uses a logging level
  138               of OFF as the default to indicate that it cannot be filtered. These events can be
  139               formatted for printing using the
  140               <a class="javadoc" href="../log4j-core/apidocs/org/apache/logging/log4j/core/layout/StructuredDataLayout.html">StructuredDataLayout</a>.
  141             </p>
  142           </subsection>
  143         </section>
  144     </body>
  145 </document>