user2395365
user2395365

Reputation: 2149

How to configure slf4j and logback to allow one class to log to a separate file?

I have one Java class that is multithreaded and I want it to log to a separate file. I'm using Dropwizard which uses logback and is configured in my YAML file like this:

    logging:
  # The default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL.
  level: INFO
  # Logger-specific levels.
  loggers:
    # Sets the level for 'com.example.app' to DEBUG.
    com.mycode: DEBUG

  appenders:
    - type: console
      threshold: DEBUG
    - type: file
      threshold: INFO
      logFormat: "%-6level [%d{HH:mm:ss.SSS}] [%t] %logger{5} - %X{code} %msg %n"
      currentLogFilename: /tmp/fingage.log
      archivedLogFilenamePattern: /tmp/project-%d{yyyy-MM-dd}-%i.log.gz
      archivedFileCount: 7
      timeZone: UTC
      maxFileSize: 10MB

Inside my special class I was trying something like:

//Obtain an instance of LoggerContext
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    //Create a new FileAppender
    FileAppender<ILoggingEvent> file = new FileAppender<ILoggingEvent>();
    file.setName("FileLogger");
    file.setFile("specialclass.log");
    file.setContext(context);
    file.setAppend(true);

    //Filter out anything < WARN
    ThresholdFilter warningFilter = new ThresholdFilter();
    warningFilter.setLevel("WARN");
    warningFilter.setContext(context);
    warningFilter.start();
    file.addFilter(warningFilter);

    //Message Encoder
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setContext(context);
    ple.setPattern("%date %level [%thread] %logger{10} %msg%n");
    ple.start();
    file.setEncoder(ple);

    file.start();

    //Get ROOT logger, and add appender to it
    log = context.getLogger(MySpecialClass.class);
    log.setLevel(Level.DEBUG);
    log.addAppender(file);

    log.info("Hello Special Class");

Unfortunately it doesn't appear to change anything, although I do a see a blank file specialclass.log and my log message appears only in the CONSOLE.

Upvotes: 0

Views: 59

Answers (1)

user2395365
user2395365

Reputation: 2149

Answer is to add the following in dropwizard YAML file:

    logging:
  # The default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL.
  level: INFO
  # Logger-specific levels.
  loggers:
    
    com.mycode:
        level: DEBUG
        additive: false 
        appenders:
          - type: file
            currentLogFilename: /tmp/myclass.log
            

  appenders:
    - type: console
      threshold: DEBUG
    - type: file
      threshold: INFO
      logFormat: "%-6level [%d{HH:mm:ss.SSS}] [%t] %logger{5} - %X{code} %msg %n"
      currentLogFilename: /tmp/project.log
      archivedLogFilenamePattern: /tmp/project-%d{yyyy-MM-dd}-%i.log.gz
      archivedFileCount: 7
      timeZone: UTC
      maxFileSize: 10MB

Upvotes: 0

Related Questions