Log4j2 ThreadContext Fish Tagging Logs of Same Transaction in java

View: 494    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Javascript   Fields: Other

9 point/3 review File has been tested

Log4j2 ThreadContext allows you to tag the log statements with multiple unique tags to analyze logs while diagnose a problem in runtime – mostly in multithreaded applications where applications generate plenty of logging in short duration.

Introduction

Log4j2 ThreadContext allows you to tag the log statements with multiple unique tags to analyze logs while diagnose a problem in runtime – mostly in multithreaded applications where applications generate plenty of logging in short duration. E.g. You may want to scan all logs for a particular user transactions or complete session. This process is also called fish tagging (i.e. add some extra context information in every log statement). This fish tagging can help using the automated tools for logs such as Splunk.

Let’s see how we can use ThreadContext class for fish tagging in log4j2.

Add Context information in ThreadContext

To uniquely stamp each request, ThreadContext provide put(String key, String value) method which accept a key and it’s value. You can add as many tags as you need to capture whole context information. Note that all methods of the ThreadContext class are static.

package com.howtodoinjava.log4j2.examples;
 
import java.util.UUID;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
 
public class Log4j2HelloWorldExample 
{
    private static final Logger LOGGER = LogManager.getLogger(Log4j2HelloWorldExample.class.getName());
     
    public static void main(String[] args) 
    {
        //Add context information
        ThreadContext.put("id", UUID.randomUUID().toString());
        ThreadContext.put("ipAddress", "192.168.21.9");
         
        LOGGER.debug("Debug Message Logged !!");
        LOGGER.info("Info Message Logged !!");
        LOGGER.debug("Another Debug Message !!");
         
        //Clear the map
        ThreadContext.clearMap();
         
        LOGGER.debug("Thread Context Cleaned up !!");
        LOGGER.debug("Log message with no context information !!");
    }
}

Or you can use ThreadContext’s Stack implemeration with ThreadContext.push(String value) as below :

//Add context information
ThreadContext.push(UUID.randomUUID().toString());
ThreadContext.push("192.168.21.9");
 
LOGGER.debug("Debug Message Logged !!");
LOGGER.info("Info Message Logged !!");
LOGGER.debug("Another Debug Message !!");
 
//Clear the map
ThreadContext.clearStack();
 
LOGGER.debug("Thread Context Cleaned up !!");
LOGGER.debug("Log message with no context information !!");

After the transaction is over or context information is no more required, you can empty the information usingThreadContext.clearMap() method.

Modify conversion pattern in log4j2.xml

Now to print above tags in log statements, you need to modify the conversion pattern in your log4j2 configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%X{id}] [%X{ipAddress}] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="debug" additivity="false">
            <AppenderRef ref="console" />
        </Root>
    </Loggers>
</Configuration>
  • Use %X by itself to include the full contents of the Map.
  • Use %X{key} to include the specified key.
  • Use %x to include the full contents of the Stack.

Now when you run the above code – you will get below output:

[DEBUG] 2016-06-21 13:09:56.485 [main] [7cdd4cf0-2c26-4b81-b374-1adce3781499] [192.168.21.9] Log4j2HelloWorldExample - Debug Message Logged !!
[INFO ] 2016-06-21 13:09:56.487 [main] [7cdd4cf0-2c26-4b81-b374-1adce3781499] [192.168.21.9] Log4j2HelloWorldExample - Info Message Logged !!
[DEBUG] 2016-06-21 13:09:56.487 [main] [7cdd4cf0-2c26-4b81-b374-1adce3781499] [192.168.21.9] Log4j2HelloWorldExample - Another Debug Message !!
[DEBUG] 2016-06-21 13:09:56.487 [main] [] [] Log4j2HelloWorldExample - Thread Context Cleaned up !!
[DEBUG] 2016-06-21 13:09:56.487 [main] [] [] Log4j2HelloWorldExample - Log message with no context information !!

As you can see that first three log statements have context information added to them – and other two statements do not have such information.

Happy Learning !!

Log4j2 ThreadContext Fish Tagging Logs of Same Transaction in java

Log4j2 ThreadContext Fish Tagging Logs of Same Transaction in java Posted on 17-08-2016  Log4j2 ThreadContext allows you to tag the log statements with multiple unique tags to analyze logs while diagnose a problem in runtime – mostly in multithreaded applications where applications generate plenty of logging in short duration. 3/10 494

Comment:

To comment you must be logged in members.

Files with category

  • JUnit 5 State Of The Union using java

    View: 633    Download: 0   Comment: 0   Author: none  

    JUnit 5 State Of The Union using java

    Category: Javascript
    Fields: Other

    1.5/3 review
    JUnit 5 has been under development for about 14 months now and the prototype is almost a year old. Time to summarize what happened so far, where the project stands, and where it’s going.

  • Getting Started with Dropwizard using java

    View: 736    Download: 0   Comment: 0   Author: none  

    Getting Started with Dropwizard using java

    Category: Javascript
    Fields: Other

    1.5/3 review
    Dropwizard is a framework for building RESTful web services in Java. In this tutorial we’re going to have a look at how to get started with developing a Dropwizard application by building a new service from scratch.

  • Build Query NULL Value in MySql

    View: 340    Download: 0   Comment: 0   Author: none  

    Build Query NULL Value in MySql

    Category: Javascript
    Fields: Other

    2.5/2 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • Manage Your JavaScript Application State with MobX

    View: 406    Download: 0   Comment: 0   Author: none  

    Manage Your JavaScript Application State with MobX

    Category: Javascript
    Fields: Other

    2.25/2 review
    This article was peer reviewed by Michel Weststrate and Aaron Boyer. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

  • Build Bringing Pages to Life with the Web Animations API

    View: 364    Download: 0   Comment: 0   Author: none  

    Build Bringing Pages to Life with the Web Animations API

    Category: Javascript
    Fields: Other

    3/3 review
    This article is by guest author Dudley Storey. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • How to Style Google Custom Search Manually

    View: 346    Download: 0   Comment: 0   Author: none  

    How to Style Google Custom Search Manually

    Category: Javascript
    Fields: Other

    0/0 review
    Website owners very often decide on using Google’s Custom Search Engine (GCSE) for searching through their content instead of using built-in and/or custom search functionality. The reason is simple – it’s much less work, and most often it does the...

  • Test React Components Using Jest

    View: 5116    Download: 0   Comment: 0   Author: none  

    Test React Components Using Jest

    Category: Javascript
    Fields: Other

    4.5/1 review
    This article is by guest author Jack Franklin. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • Programming Question Reverse String without using String function

    View: 821    Download: 0   Comment: 0   Author: none  

    Programming Question Reverse String without using String function

    Category: Javascript
    Fields: Other

    4.5/1 review
    Write a program to reverse string without using string function. You don’t have to use any in-built string library function. This problem can be solved by multiple approaches. Let’s check it.

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd