Java Code Examples for ch.qos.logback.classic.Logger#addAppender()

The following examples show how to use ch.qos.logback.classic.Logger#addAppender() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogbackLogManager.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private void configureFile(LoggingConfig.FileConfig fileConfig, Logger rootLogger) {
    if (fileConfig.isEnabled()) {
        FileAppender<ILoggingEvent> appender;
        TimeBasedRollingPolicy rollingPolicy = buildRollingPolicy(fileConfig);
        if (rollingPolicy != null) {
            appender = new RollingFileAppender<>();
            ((RollingFileAppender) appender).setRollingPolicy(rollingPolicy);
        } else {
            appender = new FileAppender<>();
        }
        appender.setContext(context);
        appender.setFile(fileConfig.getPath());
        appender.setEncoder(buildEncoder(fileConfig, DEFAULT_FILE_PATTERN));
        appender.start();
        rootLogger.addAppender(appender);
    }
}
 
Example 2
Source File: LogbackLoggingConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example 3
Source File: DefaultMetricsLogbackConfigurator.java    From lambda-monitoring with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(LoggerContext loggerContext) {
    addInfo("Setting up default configuration.");

    NonMetricsConsoleAppender nonMetricsConsoleAppender = new NonMetricsConsoleAppender();
    nonMetricsConsoleAppender.setContext(loggerContext);
    nonMetricsConsoleAppender.setName("CONSOLE");
    nonMetricsConsoleAppender.start();

    MetricsConsoleAppender metricsConsoleAppender = new MetricsConsoleAppender();
    metricsConsoleAppender.setContext(loggerContext);
    metricsConsoleAppender.setName("METRICS");
    metricsConsoleAppender.start();

    Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);
    rootLogger.addAppender(nonMetricsConsoleAppender);
    rootLogger.addAppender(metricsConsoleAppender);
}
 
Example 4
Source File: LogbackController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 
 * @param name The name of the logger we want to manipulate the level of
 * @param level The new log level
 * @return The list of log levels configured and their settings
 */
@RequestMapping(value = "set/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> set(@PathVariable("name")
final String name, @PathVariable("level")
final String level) {
    final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
    synchronized (ctx) {
        Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME);
        Logger logger = ctx.getLogger(name);
        if (logger != null) {
            logger.setLevel(Level.toLevel(level));
            logger.setAdditive(false);
            for (Iterator<Appender<ILoggingEvent>> it = root.iteratorForAppenders(); it.hasNext();) {
                logger.addAppender(it.next());
            }
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 5
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 6 votes vote down vote up
/**
 * Configure logging with default behavior and log to syslog.
 *
 * @param ident Syslog ident to use.
 * @param level logging level to use.
 * @param host Hostname or IP address of syslog host.
 * @param port Port to connect to syslog on.
 * @param loggerName Name of the logger to which the syslog appender will be added
 * @param replaceNewLines configures new lines replacement in the messages
 */
public static void configureSyslogDefaults(final String ident, final Level level,
                                           final String host, final int port,
                                           final String loggerName,
                                           final ReplaceNewLines replaceNewLines) {
  final Logger logger = (Logger) LoggerFactory.getLogger(loggerName);

  // Setup context
  final LoggerContext context = setupLoggerContext(logger, ident);

  // Setup syslog output
  logger.addAppender(getSyslogAppender(context, host, port, replaceNewLines));

  // Setup logging level
  logger.setLevel(level.logbackLevel);

  // Log uncaught exceptions
  UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler();
}
 
Example 6
Source File: DatadogSecretsDoNotLeakWhenApiCalledFunctionalTest.java    From kayenta with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  listAppender = new ListAppender<>();
  Logger mockLogger =
      (Logger) LoggerFactory.getLogger("DatadogSecretsDoNotLeakWhenApiCalledFunctionalTest");
  mockLogger.addAppender(listAppender);
  listAppender.start();

  RetrofitClientFactory retrofitClientFactory = new RetrofitClientFactory();
  retrofitClientFactory.retrofitLogLevel = "BASIC";
  retrofitClientFactory.createRetrofitLogger =
      (type) -> {
        return new Slf4jRetrofitLogger(mockLogger);
      };

  objectMapper = new ObjectMapper();
  datadogRemoteService =
      DatadogConfiguration.createDatadogRemoteService(
          retrofitClientFactory,
          objectMapper,
          new RemoteService().setBaseUrl("http://localhost:" + mockServerRule.getPort()),
          new OkHttpClient());
}
 
Example 7
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 6 votes vote down vote up
/**
 * Configure logging with the LogstashEncoder library.
 * (https://github.com/logstash/logstash-logback-encoder)
 *
 * An appender is configured to send the log messages to stdout. It is expected something like
 * a Docker container will capture these logs for further processing.
 *
 */
public static void configureLogstashEncoderDefaults(final Level level) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
  final LoggerContext context = rootLogger.getLoggerContext();

  context.reset();

  final CustomLogstashEncoder encoder = new CustomLogstashEncoder().setupStackdriver();
  encoder.setContext(context);
  encoder.start();

  final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
  appender.setTarget("System.out");
  appender.setName("stdout");
  appender.setEncoder(encoder);
  appender.setContext(context);
  appender.start();

  rootLogger.addAppender(appender);
  rootLogger.setLevel(level.logbackLevel);

  UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler();
}
 
Example 8
Source File: GelfTcpAppenderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Logger setupLogger() {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    final GelfEncoder gelfEncoder = new GelfEncoder();
    gelfEncoder.setContext(lc);
    gelfEncoder.setOriginHost("localhost");
    gelfEncoder.start();

    final Logger logger = (Logger) LoggerFactory.getLogger(LOGGER_NAME);
    logger.addAppender(buildAppender(lc, gelfEncoder));
    logger.setAdditive(false);

    return logger;
}
 
Example 9
Source File: FlumeLoggerLoader.java    From chassis with Apache License 2.0 5 votes vote down vote up
public synchronized void installFlumeAppender() {
	LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	appender.setContext(logContext);
	appender.start();

	Logger logger = logContext.getLogger(Logger.ROOT_LOGGER_NAME);

	if (logger.getAppender(appender.getName()) == null) {
		logger.addAppender(appender);
	}
}
 
Example 10
Source File: LogUtils.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the appenders for command line.
 */
public static void setAppendersForCommandLine() {
    Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER);

    LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

    rootLogger.detachAndStopAllAppenders();

    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();

    PatternLayoutEncoder consolePatternLayoutEncoder = new PatternLayoutEncoder();
    consolePatternLayoutEncoder.setPattern("%msg%n");
    consolePatternLayoutEncoder.setContext(context);
    consolePatternLayoutEncoder.start();

    consoleAppender.setEncoder(consolePatternLayoutEncoder);
    consoleAppender.start();

    rootLogger.addAppender(consoleAppender);

    ((Logger) LoggerFactory.getLogger("uk.org.lidalia")).setLevel(Level.ERROR);
    ((Logger) LoggerFactory.getLogger("org.nd4j")).setLevel(Level.ERROR);
    ((Logger) LoggerFactory.getLogger("org")).setLevel(Level.ERROR);
    ((Logger) LoggerFactory.getLogger("io")).setLevel(Level.ERROR);

    ((Logger) LoggerFactory.getLogger("ai")).setLevel(Level.INFO);
}
 
Example 11
Source File: LogbackConfigurator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
public final void root(Level level, Appender<ILoggingEvent>... appenders) {
	Logger logger = this.context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
	if (level != null) {
		logger.setLevel(level);
	}
	for (Appender<ILoggingEvent> appender : appenders) {
		logger.addAppender(appender);
	}
}
 
Example 12
Source File: WildcardMapTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
{
    m_listAppender = new ListAppender<>();
    m_listAppender.start();

    Logger root = (Logger) LoggerFactory.getLogger(WildcardMap.class);
    root.addAppender(m_listAppender);

    map = new WildcardMap<>();
}
 
Example 13
Source File: LogbackContainer.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 *
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    // appender
    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(loggerContext);
    fileAppender.setName("application");
    fileAppender.setFile(file);
    fileAppender.setAppend(true);

    // policy
    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
    policy.setContext(loggerContext);
    policy.setMaxHistory(maxHistory);
    policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
    policy.setParent(fileAppender);
    policy.start();
    fileAppender.setRollingPolicy(policy);

    // encoder
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
    encoder.start();
    fileAppender.setEncoder(encoder);

    fileAppender.start();

    rootLogger.addAppender(fileAppender);
    rootLogger.setLevel(Level.toLevel(level));
    rootLogger.setAdditive(false);
}
 
Example 14
Source File: LoggingFactory.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public static void bootstrap() {

        // Initially configure for WARN+ console logging
        final LoggingConfiguration.ConsoleConfiguration console = new LoggingConfiguration.ConsoleConfiguration();
        console.setEnabled(true);
        console.setTimeZone(TimeZone.getDefault());
        //console.setThreshold(Level.DEBUG);

        final Logger root = getCleanRoot();
        root.addAppender(LogbackFactory.buildConsoleAppender(console, root.getLoggerContext(), null));
    }
 
Example 15
Source File: LogbackContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 * 
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.detachAndStopAllAppenders();

	// appender
	RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
	fileAppender.setContext(loggerContext);
	fileAppender.setName("application");
	fileAppender.setFile(file);
	fileAppender.setAppend(true);

	// policy
	TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
	policy.setContext(loggerContext);
	policy.setMaxHistory(maxHistory);
	policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
	policy.setParent(fileAppender);
	policy.start();
	fileAppender.setRollingPolicy(policy);

	// encoder
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
	encoder.start();
	fileAppender.setEncoder(encoder);
	
	fileAppender.start();

	rootLogger.addAppender(fileAppender);
	rootLogger.setLevel(Level.toLevel(level));
	rootLogger.setAdditive(false);
}
 
Example 16
Source File: LogbackCapturingAppender.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
private void addAppender(final Logger logger) {
    logger.setLevel(Level.ALL);
    logger.addAppender(this);
    this.start();
}
 
Example 17
Source File: LogUtils.java    From konduit-serving with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the file appender with the name of "FILE" if needed. If it's already been setup,
 * it would be ignored.
 */
public static void setAppendersForRunCommand(String serverId) {
    String logFilePath = new File(DirectoryFetcher.getCommandLogsDir(), serverId + ".log").getAbsolutePath();

    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();

    Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER);

    rootLogger.detachAndStopAllAppenders();

    ((Logger) LoggerFactory.getLogger("uk.org.lidalia")).setLevel(Level.INFO);
    ((Logger) LoggerFactory.getLogger("org.nd4j")).setLevel(Level.INFO);
    ((Logger) LoggerFactory.getLogger("org")).setLevel(Level.INFO);
    ((Logger) LoggerFactory.getLogger("io")).setLevel(Level.INFO);

    LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setName("FILE");
    fileAppender.setFile(logFilePath);
    fileAppender.setAppend(false);
    fileAppender.setContext(context);

    PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
    patternLayoutEncoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    patternLayoutEncoder.setContext(context);
    patternLayoutEncoder.start();

    fileAppender.setEncoder(patternLayoutEncoder);
    fileAppender.start();

    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setName("CONSOLE");
    consoleAppender.setContext(context);
    consoleAppender.setEncoder(patternLayoutEncoder);
    consoleAppender.start();

    rootLogger.addAppender(fileAppender);
    rootLogger.addAppender(consoleAppender);

    log.info("Logging file at: {}", logFilePath);
}
 
Example 18
Source File: AnimalActivityUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Before
public void setup() {
    final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    logger.addAppender(mockAppender);
}
 
Example 19
Source File: LogbackListAppender.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 将此appender添加到logger中.
 */
public void addToLogger(String loggerName) {
	Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
	logger.addAppender(this);
}
 
Example 20
Source File: LogbackListAppender.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 将此appender添加到logger中.
 */
public void addToLogger(String loggerName) {
	Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
	logger.addAppender(this);
}