折腾:
【记录】IntelliJ IDEA中使用Java的日志库tinylog记录日志
期间,虽然已经可以实现了最最基本的console和file的log的配置,包括level等,但是发现有个问题:因为我希望console和file的2个writer的format和level都不同
却无法同时传入
参考:
说了,可以给Configurator.currentConfig的writer传入format:
Configurator.currentConfig() .writer(new ConsoleWriter(), "{level}: {message}") .addWriter(new FileWriter("log.txt"), "{class}.{method}()\t{message}") .activate();
也可以传入level:
Configurator.currentConfig() .writer(new ConsoleWriter(), Level.TRACE) .addWriter(new FileWriter("log.txt"), Level.INFO) .activate();
但是不知道如何两个都传入
后来还是看到了:
才看到了写法:
addWriter(Writer writer, Level level, String formatPattern) writer(Writer writer, Level level, String formatPattern)
去试试
String logFilename = "../log/EmulateLoginBaidu.log"; FileWriter fileWriter = new FileWriter(logFilename); ConsoleWriter consoleWriter = new ConsoleWriter(); Level fileWriterLevel = Level.TRACE; Level consoleWriterLevel = Level.DEBUG; String consoleFormat = "{date:YYMMdd HH:mm:ss} {class}.{method} {{level}|min-size=8}: {message}"; String fileFormat = "{date:yyyyMMdd HH:mm:ss} [{thread}] {class}.{method} {{level}|min-size=8}: {message}"; Configurator.currentConfig() .writer(consoleWriter, consoleWriterLevel, consoleFormat) .addWriter(fileWriter, fileWriterLevel, fileFormat) .activate();
是可以的分别起到效果的:
- Console: >=DEBUG才输出,格式是YYMMdd
- File:>=TRACE都输出,格式是yyyyMMdd
【总结】
tinylog中给console和file的不同writer,在初始化时传入不同的参数,比如level,format等,可以用:
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Level; import org.pmw.tinylog.Configurator; import org.pmw.tinylog.writers.ConsoleWriter; import org.pmw.tinylog.writers.FileWriter; String logFilename = "log/EmulateLoginBaidu.log"; FileWriter fileWriter = new FileWriter(logFilename); ConsoleWriter consoleWriter = new ConsoleWriter(); Level fileWriterLevel = Level.TRACE; Level consoleWriterLevel = Level.DEBUG; String consoleFormat = "{date:YYMMdd HH:mm:ss} {class}.{method} {{level}|min-size=8}: {message}"; String fileFormat = "{date:yyyyMMdd HH:mm:ss} [{thread}] {class}.{method} {{level}|min-size=8}: {message}"; Configurator.currentConfig() .writer(consoleWriter, consoleWriterLevel, consoleFormat) .addWriter(fileWriter, fileWriterLevel, fileFormat) .activate();
即可。
详见:
转载请注明:在路上 » 【已解决】tinylog中如何初始化同时给console和file传入不同的level和format的配置