Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Logback output to console programmatically but append to file

I have setup Logback file appender programmatically and set log level into ALL. The reason was to set log level ALL i wanted to log file contains all log details like(INFO,DEBUG,WARN and etc...)But i want to avoid those details from the console.If anyone knows please let me know how can i disable Logback output to console programmatically.

Logger code snippet

Reference

private static Logger createLoggerFor(String string, String file) {
          LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
          PatternLayoutEncoder ple = new PatternLayoutEncoder();

          ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
          ple.setContext(lc);
          ple.start();
          FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
          fileAppender.setFile(file);
          fileAppender.setEncoder(ple);
          fileAppender.setContext(lc);
          fileAppender.start();

          Logger logger = (Logger) LoggerFactory.getLogger(string);
          logger.addAppender(fileAppender);
          logger.setLevel(Level.ALL);
          logger.setAdditive(false); /* set to true if root should log too */

          return logger;
    }

Note:When i set log level WARN or DEBUG details doesnt show in the log file as well as console out put.But i want to log every details in to log file including INFO.

like image 460
gihan-maduranga Avatar asked Nov 25 '25 10:11

gihan-maduranga


2 Answers

From the docs:

Assuming the configuration files logback-test.xml or logback.xml are not present, logback will default to invoking BasicConfigurator which will set up a minimal configuration. This minimal configuration consists of a ConsoleAppender attached to the root logger.

If you want to disable all console output, you should try removing the default ConsoleAppender. According to the BasicConfigurator source, this appender's name is "console". So you could try (untested):

logger.detachAppender("console");

I highly recommend moving these programmatic configurations into a logback.xml file, and only changing the configuration programmatically when necessary. The config file is more explicit and easier to manage in my opinion.

like image 112
Kyle McVay Avatar answered Nov 28 '25 00:11

Kyle McVay


This works for me

logger.setAdditivity(false);
like image 39
Albin Avatar answered Nov 27 '25 23:11

Albin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!