capture logs in a test

Viewed 460

I'm trying to capture bean allocation logs in a test - I've got code that I've tested, and will successfully capture logs from my classes - but when I try to do it on spring classes it is seemingly not working - here is the code I use to try and capture:

    LoggerContext context = (LoggerContext) (LoggerFactory.getILoggerFactory());
    Logger log = context.getLogger("org.springframework.beans.factory.support.DefaultListableBeanFactory");
    log.setLevel(Level.DEBUG);
    MyAppender appender = new MyAppender();
    appender.setContext( context);
    log.addAppender( appender  );
    SpringApplication newApplication = new SpringApplication( Application.class);
    newApplication.run( new String [] {});

Now if I trace in and look at the logger that spring is using - it looks like a completely different style of logger - (its hooked to a logmanager, not a loggercontext) - and go into that and it seems like it might be a different context?

Any idea what I'm doing wrong, and how I can in a unit test capture spring bean creation logs?

3 Answers

Spring boot is using Logback logger by default It uses LogbackLoggingSystem implementation which extends from AbstractLoggingSystem Spring boot LoggingSystem runs before context is initialized To override default properties you can define logback.xml or logback-spring.xml Or you can use application.yml or properties file to define log configurations :

logging.level.* : It is used as prefix with package name to set log level. logging.file : It configures a log file name to log message in file. We can also configure file name with absolute path. logging.path : It only configures path for log file. Spring boot creates a log file with name spring.log logging.pattern.console : It defines logging pattern in console. logging.pattern.file: It defines logging pattern in file. logging.pattern.level: It defines the format to render log level. Default is %5p.

As documentation says: You can force Spring Boot to use a particular logging system by using the org.springframework.boot.logging.LoggingSystem system property. The value should be the fully qualified class name of a LoggingSystem implementation. You can also disable Spring Boot’s logging configuration entirely by using a value of none.

If you use static Loggers in your Class under Test, you could use Powermock to mock the logger and assert the output, as descirbed in this question. We use it in our Spring-Tests and formatting and style is the same.

for anyone interested - this finally worked for me:

Logger logger = Logger.getLogger(
        "org.springframework.beans.factory.support.DefaultListableBeanFactory");
logger.addHandler( this );
logger.setLevel( java.util.logging.Level.FINE);
_logger = logger;

now I can capture, trace and time all bean allocations.

Related