Is there a Logback Layout that Creates JSON Objects with Message Parameters as Attributes?

后端 未结 5 754
天命终不由人
天命终不由人 2021-02-02 09:32

I want to send log events to Loggly as JSON objects with parameterized string messages. Our project currently has a lot of code that looks like this:

String some         


        
5条回答
  •  悲哀的现实
    2021-02-02 09:38

    So for me I was trying to log execution times, I created a pojo called ExecutionTime with name, method, class, duration.

    I was then able to create it:

    ExecutionTime time = new ExecutionTime("Controller Hit", methodName, className, sw.getTotalTimeMillis());
    

    For logging I then used:

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    logger.info(append("metric", time), time.toString());
    

    Make sure you have:

    import static net.logstash.logback.marker.Markers.append;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    

    This will log something like this:

    {  
       "ts":"2017-02-16T07:41:36.680-08:00",
       "msg":"ExecutionTime [name=Controller Hit, method=setupSession, className=class com.xxx.services.controllers.SessionController, duration=3225]",
       "logger":"com.xxx.services.metrics.ExecutionTimeLogger",
       "level":"INFO",
       "metric":{  
          "name":"Controller Hit",
          "method":"setupSession",
          "className":"class com.xxx.services.controllers.SessionController",
          "duration":3225
       }
    }
    

    Might be a different set up as I was using logback-spring.xml to output my logs to json:

    
    
        
        
        
            app/logs/${PROJECT_ID}.json.log
            
                
                    ts
                    msg
                    [ignore]
                    [ignore]
                    logger
                    [ignore]
                
            
            
                10
                app/logs/${PROJECT_ID}.json.log.%i
            
            
                20MB
            
        
        
            
            
        
        
            
        
    
    

提交回复
热议问题