简体   繁体   中英

Is there any way to log System.err to a file in Logback?

I have an old project that is doing

catch (Exception e) {
e.printStacktrace();
}

all over the place. Now I want to log those stacktraces to a file using Logback. I couldn't find any solution online.

Is there a way in Logback, to log System.Error statements to a file? I've tried the following but doesn't work, it only writes STDOUT logs to the file.

If anyone could help, it'd be great, thanks!

def DEFAULT_PATTERN = "%d [%thread] %-5level %logger - %msg%n"

appender("STDOUT", ConsoleAppender) {
    encoder(PatternLayoutEncoder) { 
        pattern = DEFAULT_PATTERN 
        charset = Charset.forName("UTF-8")
    }
}

appender("SYSERR", ConsoleAppender) {
    encoder(PatternLayoutEncoder) { 
        pattern = DEFAULT_PATTERN 
        charset = Charset.forName("UTF-8")
    }
    target = "System.err"
}

appender("FILE", RollingFileAppender) {
  file = "logs/stdout.log"
  append = true
  encoder(PatternLayoutEncoder) {
    pattern = DEFAULT_PATTERN
    charset = Charset.forName("UTF-8")
  }
  filter(ch.qos.logback.classic.filter.ThresholdFilter) {
    level = INFO
  }
  rollingPolicy(ch.qos.logback.core.rolling.TimeBasedRollingPolicy) {
    fileNamePattern = "logs/stdout-%d{yyyy-MM-dd}.%i.log"
    maxHistory = 10
    timeBasedFileNamingAndTriggeringPolicy(ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP) {
      maxFileSize = "1MB"
    }
  }
}

appender("ERROR", RollingFileAppender) {
  file = "logs/errors.log"
  append = true
  encoder(PatternLayoutEncoder) {
    pattern = DEFAULT_PATTERN
    charset = Charset.forName("UTF-8")
  }
  filter(ch.qos.logback.classic.filter.ThresholdFilter) {
    level = ERROR
  }
  rollingPolicy(ch.qos.logback.core.rolling.TimeBasedRollingPolicy) {
    fileNamePattern = "logs/errors-%d{yyyy-MM-dd}.%i.log"
    maxHistory = 10
    timeBasedFileNamingAndTriggeringPolicy(ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP) {
      maxFileSize = "1MB"
    }
  }
}

/* Make Spring less verbose. */
//logger("org.springframework", INFO)
//logger("org.springframework.web.servlet", INFO)

/* Quieten Thymeleaf. */
//logger("org.thymeleaf", INFO)

/* Jetty can be really noisy on a shaded jar. */
//logger("org.eclipse.jetty.webapp.WebAppClassLoader", INFO)
//logger("org.eclipse.jetty.util.resource.JarResource", INFO)

/* Quieten Jetty in general. */
//logger("org.eclipse", DEBUG);

def appenders = []
appenders.add("STDOUT")
appenders.add("SYSERR")
appenders.add("FILE")
appenders.add("ERROR")

root(INFO, appenders)

Ended up using a solution that redirects System err to a custom output printstream

log4j redirect stdout to DailyRollingFileAppender

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM