Dropwizard doesn't log custom loggers to file

后端 未结 2 1254
小蘑菇
小蘑菇 2020-11-30 10:31

I have a dropwizard app, where I configured logger appenders to file as follows:

logging:
  level: INFO

  loggers:
    \"mylogger\": INFO
    \"com.path.to.         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 11:11

    You can implement separate logger with the dropwizard using logback.

    1.Configure logger in your Application class (i.e application start point with main method) like below.

    LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
    context.reset();
    ContextInitializer initializer = new ContextInitializer(context);
    initializer.autoConfig();
    

    2.Configure logback.xml like below.

    
    
    
        /var/log/applicationname-mylogger.log
        
            
            logFile.%d{yyyy-MM-dd}.log
            
            30
        
        false
        
            %-5relative %-5level %logger{35} - %msg%n
        
    
    
        /var/log/applicationame-com.path.to.class.log
        
            
            logFile.%d{yyyy-MM-dd}.log
            
            30
        
        false
        
            %-5relative %-5level %logger{35} - %msg%n
        
    
    
        
        
    
    
        
        
    
    
    

    3.Now use logger

    static final Logger OpLogger = LoggerFactory.getLogger("mylogger");
    static final Logger classLogger = LoggerFactory.getLogger("com.path.to.class");
    

    EDIT :

    I have try to implement the same logger in my example project. It works fine in my case. We can not use the LOGGER before the Dropwizard application initialize. The Dropwizard initialized only when you call

      new ExampleApplication().run(args);
    

    So, if logger is used before Dropwizard initialized, your log will not be there. I have tried to implemented scenario with main method. The first log statement is not printed as we have used logger before the Dropwizard initialization, but the second log statement will be printed.

      OpLogger.info("test 1");
      new ExampleApplication().run(args);
      ClassLogger.info("test 2);
    

    Hope this will help you out to solve your problem.

提交回复
热议问题