Best way to write custom json messages using log4j2

后端 未结 3 1365
不思量自难忘°
不思量自难忘° 2020-12-30 13:54

I have been using log4j for different kind of projects and have some experience with log4j2. All implementations used the default appender and layout. Currently i need to wr

3条回答
  •  Happy的楠姐
    2020-12-30 14:34

    If you're looking for a way to generate customized JSON log messages without any of the "noise" added by log4j2 you could create an implementation of the Message interface and use a different layout - for example PatternLayout. Below is an example of this approach:

    First a class to implement Message inferface

    import java.util.HashMap;
    import java.util.Map;
    
    import org.apache.logging.log4j.message.Message;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class JSONMessage implements Message {
    
        private static final long serialVersionUID = 538439258494853324L;
        private String messageString;
        private static final Gson GSON = new GsonBuilder()
                .setPrettyPrinting()
                .create();
    
        public JSONMessage(){
            this(null);
        }
    
        public JSONMessage(Object msgObj){
            parseMessageAsJson(msgObj);
        }
    
        public JSONMessage(String msgStr){
            Map msgObj = new HashMap<>();
            msgObj.put("message", msgStr);
            parseMessageAsJson(msgObj);
        }
    
        private void parseMessageAsJson(Object msgObj){
            messageString = GSON.toJson(msgObj);
        }
    
        @Override
        public String getFormattedMessage() {
            return messageString;
        }
    
        @Override
        public String getFormat() {
            return messageString;
        }
    
        @Override
        public Object[] getParameters() {
            return null;
        }
    
        @Override
        public Throwable getThrowable() {
            return null;
        }
    
    }
    

    Next the log4j2.xml configuration:

    
    
        
            
                    
            
        
    
        
            
                
            
        
    
    

    Now a simple application class to generate a log event

    import java.util.HashMap;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    
    public class App {
    
        private static final Logger logger = LogManager.getLogger();
    
        public static void main( String[] args )
        {
            HashMap msgMap = new HashMap<>();
            msgMap.put("someInt", 123);
            msgMap.put("note", "Maybe you put a message here");
    
            HashMap anotherMap = new HashMap<>();
            anotherMap.put("key1", "value1");
            anotherMap.put("key2", "value2");
            msgMap.put("map", anotherMap);
            logger.info(new JSONMessage(msgMap));
        }
    }
    

    Here is some sample output:

    {
      "note": "Maybe you put a message here",
      "map": {
        "key1": "value1",
        "key2": "value2"
      },
      "someInt": 123
    }
    

    Note that I'm using Gson to create the JSON output, but you could use any library you want. Also note that this code does not generate "complete" JSON in that it does not add the square brackets at the start and end of the log or the comma between message objects.

提交回复
热议问题