Java Code Examples for ch.qos.logback.classic.PatternLayout

The following examples show how to use ch.qos.logback.classic.PatternLayout. These examples are extracted from open source projects. 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
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 2
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 Project: sylph   Source File: LogAppender.java    License: Apache License 2.0 6 votes vote down vote up
public LogAppender(int maxSizeQueue)
{
    this.maxSizeQueue = maxSizeQueue;
    this.datas = new AtomicReferenceArray<>(maxSizeQueue);

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    this.setName(consoleName);
    this.setContext(loggerContext);
    this.start();

    Logger logger = loggerContext.getLogger("ROOT");
    logger.addAppender(this);

    PatternLayout layout = new PatternLayout();
    layout.setContext(context);
    layout.setPattern("%d{yy-MM-dd HH:mm:ss} %p[%F:%L]-%m%n");
    layout.start();
    this.layout = layout;
}
 
Example 4
Source Project: logback-gelf-appender   Source File: GelfAppender.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    if (this.layout == null) {
        PatternLayout patternLayout = new PatternLayout();
        patternLayout.setContext(context);
        patternLayout.setPattern("%m %n");
        patternLayout.start();
        this.layout = patternLayout;
    }
    if (this.hostName == null || this.hostName.trim().isEmpty()) {
        try {
            this.hostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            this.hostName = "localhost";
        }
    }
    createGelfClient();
    throwableConverter.start();
    super.start();
}
 
Example 5
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 6
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 7
@Override
public void start()
{
    if (isStarted()) {
        return;
    }

    PatternLayout patternLayout = new PatternLayout();
    patternLayout.setContext(context);
    patternLayout.setPattern(PATTERN);
    patternLayout.setOutputPatternAsHeader(false);
    patternLayout.start();
    this.layout = patternLayout;

    super.start();
}
 
Example 8
Source Project: tddl5   Source File: DynamicLogback918Logger.java    License: Apache License 2.0 6 votes vote down vote up
protected Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setParent(appender);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd}");
    rolling.setContext(loggerContext);
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayout layout = new PatternLayout();
    layout.setPattern(pattern);
    layout.setContext(loggerContext);
    layout.start();
    appender.setLayout(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example 9
Source Project: tddl5   Source File: DynamicLogback918Logger.java    License: Apache License 2.0 6 votes vote down vote up
protected Appender buildDailyMaxRollingAppender(String name, String fileName, String pattern, int maxBackupIndex) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setContext(loggerContext);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd-HH}");
    rolling.setMaxHistory(maxBackupIndex);
    rolling.setParent(appender);
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayout layout = new PatternLayout();
    layout.setContext(loggerContext);
    layout.setPattern(pattern);
    layout.start();
    appender.setLayout(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example 10
Source Project: owasp-security-logging   Source File: CRLFConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	PatternLayout.defaultConverterMap.put("crlf",
			CRLFConverter.class.getName());
	// layout = new PatternLayout();

	encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%-4relative [%thread] %-5level %logger{35} - %crlf(%msg)%n");
	encoder.start();

	// Layout layout = new PatternLayout();
	// layout.setEncoder(encoder);

	mockAppender.setContext(loggerContext);
	mockAppender.setEncoder(encoder);
	mockAppender.start();

	LOGGER = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
	LOGGER.addAppender(mockAppender);
}
 
Example 11
@Before
public void setUp() {
	PatternLayout.defaultConverterMap.put("mask",
			MaskingConverter.class.getName());

	encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%-4relative [%thread] %-5level %logger{35} - %mask%n");
	encoder.start();

	mockAppender.setContext(loggerContext);
	mockAppender.setEncoder(encoder);
	mockAppender.start();

	LOGGER.addAppender(mockAppender);
}
 
Example 12
@Override
public void start() {
	patternLayout = new PatternLayout();
	patternLayout.setContext(getContext());
	patternLayout.setPattern("%date %level [%thread] %logger{10}:%line %msg%n");
	patternLayout.start();
	super.start();
}
 
Example 13
Source Project: uavstack   Source File: LogBackHookProxy.java    License: Apache License 2.0 5 votes vote down vote up
private void getAppenderInfo(FileAppender<ILoggingEvent> fileAppender, LinkedList<LogProfileInfo> list, String appid) {
    
    LogProfileInfo logProfileInfo = new LogProfileInfo();
    logProfileInfo.setLogType(LogProfileInfo.LogType.Log4j);
    logProfileInfo.setFilePath(fileAppender.getFile());
    if (appid != null) {
        logProfileInfo.setAppId(appid);
    }
    
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put(LogProfileInfo.ENGINE, "logback");

    @SuppressWarnings("rawtypes")
    LayoutWrappingEncoder encoder = (LayoutWrappingEncoder) fileAppender.getEncoder();
    Layout<?> layout = encoder.getLayout();
    if (null != layout) {
        if (layout instanceof PatternLayout) {
            PatternLayout patternLayout = (PatternLayout) encoder.getLayout();
            attributes.put(LogProfileInfo.PATTERN, patternLayout.getPattern());
        }
        else if (layout instanceof HTMLLayout) {
            attributes.put(LogProfileInfo.PATTERN, "HTMLLayout");
        }
        else if (layout instanceof XMLLayout) {
            attributes.put(LogProfileInfo.PATTERN, "XMLLayout");
        }
        else if (layout instanceof TTLLLayout) {
            attributes.put(LogProfileInfo.PATTERN, "TTCCLayout");
        }
    }

    logProfileInfo.setAttributes(attributes);
    list.add(logProfileInfo);      
}
 
Example 14
private PatternLayout buildPattern(final String pattern) {
    final PatternLayout patternLayout = new PatternLayout();
    patternLayout.setContext(getContext());
    patternLayout.setPattern(pattern);
    patternLayout.start();
    return patternLayout;
}
 
Example 15
Source Project: cf-java-logging-support   Source File: JsonEncoder.java    License: Apache License 2.0 5 votes vote down vote up
private PatternLayout getLayout(ILoggingEvent event) {
	PatternLayout layout = layouts.get(getMarker(event));
	if (layout == null) {
		layout = layouts.get(Markers.DEFAULT_MARKER);
	}
	return layout;
}
 
Example 16
Source Project: cf-java-logging-support   Source File: JsonEncoder.java    License: Apache License 2.0 5 votes vote down vote up
private void defineConverters() {
	PatternLayout.defaultConverterMap.put(CustomFieldsConverter.WORD, CustomFieldsConverter.class.getName());
	PatternLayout.defaultConverterMap.put(JsonMessageConverter.WORD, JsonMessageConverter.class.getName());
	PatternLayout.defaultConverterMap.put(ContextPropsConverter.WORD, ContextPropsConverter.class.getName());
	PatternLayout.defaultConverterMap.put(LogbackStacktraceConverter.WORD,
			LogbackStacktraceConverter.class.getName());
	PatternLayout.defaultConverterMap.put(TimestampConverter.WORD, TimestampConverter.class.getName());
	PatternLayout.defaultConverterMap.put(CategoriesConverter.WORD, CategoriesConverter.class.getName());
}
 
Example 17
Source Project: emodb   Source File: LogbackSlowQueryLogProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SlowQueryLog get() {
    Logger logger = (Logger) LoggerFactory.getLogger("sor.slow-query");
    logger.setAdditive(false);
    LoggerContext context = logger.getLoggerContext();
    logger.detachAndStopAllAppenders();

    PatternLayout logPatternLayout = new PatternLayout();
    logPatternLayout.setPattern("%-5p [%d{ISO8601," + _config.getTimeZone().getID() + "}] %m\n");
    logPatternLayout.setContext(context);
    logPatternLayout.start();

    ConsoleAppenderFactory consoleAppenderFactory = _config.getConsoleAppenderFactory();
    if (consoleAppenderFactory != null) {
        // Console is usually used only in development.  Use a synchronous appender so console output doesn't get re-ordered.
        logger.addAppender(consoleAppenderFactory.build(context, EMODB_APPLICATION_NAME, logPatternLayout));
    }

    FileAppenderFactory fileAppenderFactory = _config.getFileAppenderFactory();
    if (fileAppenderFactory != null) {
        AsyncAppender fileAsyncAppender = new AsyncAppender();
        fileAsyncAppender.addAppender(fileAppenderFactory.build(context, EMODB_APPLICATION_NAME, logPatternLayout));
        fileAsyncAppender.start();
        logger.addAppender(fileAsyncAppender);
    }

    SyslogAppenderFactory syslogAppenderFactory = _config.getSyslogAppenderFactory();
    if (syslogAppenderFactory != null) {
        AsyncAppender sysAsyncAppender = new AsyncAppender();
        sysAsyncAppender.addAppender(syslogAppenderFactory.build(context, EMODB_APPLICATION_NAME, logPatternLayout));
        sysAsyncAppender.start();
        logger.addAppender(sysAsyncAppender);
    }

    return new LogbackSlowQueryLog(logger, _config.getTooManyDeltasThreshold(), _metricRegistry);
}
 
Example 18
Source Project: nexus-public   Source File: NexusLayoutEncoder.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void start() {
  PatternLayout patternLayout = new PatternLayout();
  patternLayout.getDefaultConverterMap().put("node", NexusNodeNameConverter.class.getName());
  patternLayout.setContext(context);
  patternLayout.setPattern(getPattern());
  patternLayout.start();
  this.layout = patternLayout;
  super.start();
}
 
Example 19
Source Project: owasp-security-logging   Source File: BaseConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    PatternLayout.defaultConverterMap.put("testmask", getConverterClass());
    encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("[%thread] %-5level -masked- %testmask%n");
    encoder.start();

    mockAppender.setContext(loggerContext);
    mockAppender.setEncoder(encoder);
    mockAppender.start();
    
    LOGGER.addAppender(mockAppender);
}
 
Example 20
@Override
public Layout<ILoggingEvent> buildLayout() {
  final PatternLayout layout = new PatternLayout();
  layout.getInstanceConverterMap().put("syslogStart",
      MillisecondPrecisionSyslogStartConverter.class.getName());
  if (suffixPattern == null) {
    suffixPattern = DEFAULT_SUFFIX_PATTERN;
  }
  layout.setPattern(getPrefixPattern() + suffixPattern);
  layout.setContext(getContext());
  layout.start();
  return layout;
}
 
Example 21
Source Project: jadx   Source File: LogCollector.java    License: Apache License 2.0 5 votes vote down vote up
public static void register() {
	Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
	LoggerContext loggerContext = rootLogger.getLoggerContext();

	PatternLayout layout = new PatternLayout();
	layout.setContext(loggerContext);
	layout.setPattern("%-5level: %msg%n");
	layout.start();

	INSTANCE.setContext(loggerContext);
	INSTANCE.setLayout(layout);
	INSTANCE.start();

	rootLogger.addAppender(INSTANCE);
}
 
Example 22
Source Project: milkman   Source File: LogbackConfiguration.java    License: MIT License 4 votes vote down vote up
private void setupFileAppender(LoggerContext loggerContext) {
	RollingFileAppender<ILoggingEvent> fa = new RollingFileAppender<ILoggingEvent>();
	fa.setFile(PlatformUtil.getWritableLocationForFile("errors.log"));
	
	SizeBasedTriggeringPolicy<ILoggingEvent> sizePolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>();
	sizePolicy.setContext(loggerContext);
	sizePolicy.setMaxFileSize(FileSize.valueOf("10mb"));
	sizePolicy.start();
	fa.setTriggeringPolicy(sizePolicy);
	var policy = new FixedWindowRollingPolicy();
	policy.setMaxIndex(3);
	policy.setMinIndex(1);
	policy.setFileNamePattern("errors.%i.log.zip");
	policy.setParent(fa);
	policy.setContext(loggerContext);
	policy.start();
	fa.setRollingPolicy(policy);
	
	
	fa.setContext(loggerContext);
	fa.setName("FILE");
	
	var filter = new ThresholdFilter();
	filter.setLevel("ERROR");
	filter.start();
	fa.addFilter(filter);

	LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
	encoder.setContext(loggerContext);

	// same as
	// PatternLayout layout = new PatternLayout();
	// layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
	PatternLayout layout = new PatternLayout();
	layout.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");

	layout.setContext(loggerContext);
	layout.start();
	encoder.setLayout(layout);
	fa.setEncoder(encoder);

	
	fa.start();

	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.addAppender(fa);
}
 
Example 23
Source Project: eclair   Source File: SampleBuilder.java    License: Apache License 2.0 4 votes vote down vote up
void setPatternLayout(PatternLayout patternLayout) {
    this.patternLayout = patternLayout;
}
 
Example 24
@Test(timeout = 5000)
public void testBasic() throws InterruptedException {
	CloudWatchAppender appender = new CloudWatchAppender();
	AWSLogsClient awsLogClient = createMock(AWSLogsClient.class);
	appender.setAwsLogsClient(awsLogClient);

	appender.setMaxBatchSize(1);
	appender.setRegion("region");
	final String logGroup = "pfqoejpfqe";
	appender.setLogGroup(logGroup);
	final String logStream = "pffqjfqjpoqoejpfqe";
	appender.setLogStream(logStream);
	PatternLayout layout = new PatternLayout();
	layout.setContext(new LoggerContext());
	layout.setPattern("[%thread] %level %logger{20} - %msg%n%xThrowable");
	layout.start();
	appender.setLayout(layout);

	LoggingEvent event = new LoggingEvent();
	event.setTimeStamp(System.currentTimeMillis());
	String loggerName = "name";
	event.setLoggerName(loggerName);
	Level level = Level.DEBUG;
	event.setLevel(level);
	String message = "fjpewjfpewjfpewjfepowf";
	event.setMessage(message);

	String threadName = Thread.currentThread().getName();
	final String fullMessage = "[" + threadName + "] " + level + " " + loggerName + " - " + message + "\n";

	final PutLogEventsResult result = new PutLogEventsResult();
	String sequence = "ewopjfewfj";
	result.setNextSequenceToken(sequence);
	expect(awsLogClient.putLogEvents(isA(PutLogEventsRequest.class))).andAnswer(new IAnswer<PutLogEventsResult>() {
		@Override
		public PutLogEventsResult answer() {
			PutLogEventsRequest request = (PutLogEventsRequest) getCurrentArguments()[0];
			assertEquals(logGroup, request.getLogGroupName());
			assertEquals(logStream, request.getLogStreamName());
			List<InputLogEvent> events = request.getLogEvents();
			assertEquals(1, events.size());
			assertEquals(fullMessage, events.get(0).getMessage());
			return result;
		}
	}).times(2);
	awsLogClient.shutdown();

	// =====================================

	replay(awsLogClient);
	appender.start();
	// for coverage
	appender.start();
	appender.append(event);
	Thread.sleep(10);
	appender.append(event);
	while (appender.getEventsWrittenCount() < 2) {
		Thread.sleep(10);
	}
	appender.stop();
	verify(awsLogClient);
}
 
Example 25
@Test(timeout = 5000)
public void testInstanceName() throws InterruptedException {
	CloudWatchAppender appender = new CloudWatchAppender();
	AWSLogsClient awsLogClient = createMock(AWSLogsClient.class);
	appender.setAwsLogsClient(awsLogClient);

	appender.setMaxBatchSize(1);
	appender.setRegion("region");
	final String logGroup = "pfqoejpfqe";
	appender.setLogGroup(logGroup);
	String prefix = "logstream-";
	appender.setLogStream(prefix + "%instanceName");
	final String expectedLogStream = prefix + "unknown";
	PatternLayout layout = new PatternLayout();
	layout.setPattern("%msg");
	layout.start();
	appender.setLayout(layout);

	LoggingEvent event = new LoggingEvent();
	event.setTimeStamp(System.currentTimeMillis());
	event.setLoggerName("name");
	event.setLevel(Level.DEBUG);
	event.setMessage("message");

	final PutLogEventsResult result = new PutLogEventsResult();
	result.setNextSequenceToken("ewopjfewfj");
	expect(awsLogClient.putLogEvents(isA(PutLogEventsRequest.class))).andAnswer(new IAnswer<PutLogEventsResult>() {
		@Override
		public PutLogEventsResult answer() {
			PutLogEventsRequest request = (PutLogEventsRequest) getCurrentArguments()[0];
			assertEquals(logGroup, request.getLogGroupName());
			assertEquals(expectedLogStream, request.getLogStreamName());
			return result;
		}
	});
	awsLogClient.shutdown();

	// =====================================

	replay(awsLogClient);
	appender.start();
	appender.append(event);
	while (appender.getEventsWrittenCount() < 1) {
		Thread.sleep(10);
	}
	appender.stop();
	verify(awsLogClient);
}
 
Example 26
public PatternLayout getShortPatternLayout() {
    return shortPatternLayout;
}
 
Example 27
public void setShortPatternLayout(final PatternLayout shortPatternLayout) {
    this.shortPatternLayout = shortPatternLayout;
}
 
Example 28
public PatternLayout getFullPatternLayout() {
    return fullPatternLayout;
}
 
Example 29
public void setFullPatternLayout(final PatternLayout fullPatternLayout) {
    this.fullPatternLayout = fullPatternLayout;
}
 
Example 30
private void createLayout() {
  layout = new PatternLayout();
  layout.setPattern("%d{HH:mm:ss.SSS zzz} - %msg%n%nopex");
  layout.setContext(getContext());
  layout.start();
}