Log4j2 etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Log4j2 etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

16 Kasım 2023 Perşembe

Log4j2 Ayar Dosyası

Giriş
Log4J2 için kullanılan ayar dosyası belirli bir önceliğe göre aranıyor. Öncelik sıralaması burada tanımlı. Açıklaması şöyle
1. Log4j will inspect the "log4j2.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension. Note that this is not restricted to a location on the local file system and may contain a URL.
2. If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.
3. If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.
4. If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
5. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
6. If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath.
7. If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
8 . If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
9. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
10. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
1. DefaultConfiguration
Açıklaması şöyle
Log4j 2 provides a default configuration that will be used if no custom configuration file is provided. This default configuration is designed to work in most situations, but it may not meet all of your specific logging needs.
2. XML veya YAML Dosyası
Açıklaması şöyle
If you choose to configure Log4j 2 using a log4j2.xml or log4j2.yml file, you can place the file in your application's classpath (in our case main/java/resources), in the root of your application's jar file, or in a directory specified by the log4j.configurationFile system property.

3. Kendi Dosyam
log4j2.configurationFile ile belirtilir.

Örnek - properties dosyası
Şöyle yaparız
java ... -Dlog4j2.configurationFile=mylog.properties
Kodla şöyle yaparız
public static void main(String[] args) {
  System.setProperty("log4j2.configurationFile", "file:///.../mylog.properties");
  
}

14 Ağustos 2023 Pazartesi

Log4j2 log4j2.xml SysAppender Tanımlama - Syslog Tag

Örnek
Şöyle yaparız. Belirtilen syslog sunucusuna log gönderir.
<Syslog name="Syslog" format="RFC5424" host="127.0.0.1" port="4514" protocol="TCP" 
  appName="Hazelcast"
  newLine="true" messageId="Audit" id="hz">
  <PatternLayout pattern="%d{ISO8601} %5p |%X{test-name}| - [%c{1}] %t - %m%n"/>
</Syslog>

22 Mart 2023 Çarşamba

Log4j2 log4j2.xml İskelet

monitorInterval Alanı
Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
  <Properties>
    <Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n</Property>
  </Properties>
 
  <Appenders>
    ...
  </Appenders>
 
  <Loggers>
    ...
  </Loggers>
</Configuration>
shutdownHook Alanı
Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30" shutdownHook="disable">
   ...
</Configuration>

14 Mart 2023 Salı

Log4j2 log4j2.xml ConsoleAppender Tanımlama - Console Tag

Giriş
Açıklaması şöyle
Log4j2 supports a number of System Properties that can be used to configure various items. For example, the log4j2.skipJansi system property can be used to configure if the ConsoleAppender will try to use a Jansi output stream on Windows.
Açıklaması şöyle
writes the data to System.out or System.err with the default begin the first one (a Java best practice when logging in containers)
Örnek
Şöyle yaparız
<Appenders>
  <Console name="Console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} - %m %n"/>
  </Console>
</Appenders>
Örnek
Şöyle yaparız. Burada target System.out ama aslında normalde belirtmeye gerek yok. Varsayılan zaten bu
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30" shutdownHook="disable">
   <Appenders>
      <Console name="Console" target="SYSTEM_OUT">
         <PatternLayout pattern="%-5p|%d{ISO8601}{GMT}|%X{token}|%c{1}|%m%ex%n" />
      </Console>
   </Appenders>
   ...
</Configuration>

Log4j2 log4j2.xml FileAppender Tanımlama

Örnek
Şöyle yaparız
<Configuration name="LogToConsole" target="SYSTEM_OUT">
  <Appenders>
    <File name="FileAppender" fileName="logs/app.log.json">
      <EcsLayout serviceName="my-app"/>
    </File>
  </Appenders>

  <Loggers>
    <Root>
      <AppenderRef ref="FileAppender" />
    </Root>
    <Logger name="none.rks.Main" level="debug" additivity="false">
      <AppenderRef ref="FileAppender" />
    </Logger>
  </Loggers>
</Configuration>

26 Aralık 2022 Pazartesi

Log4j2 JsonLayout Tanımlama

Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <JsonLayout complete="false"  compact="true" eventEol="true"></JsonLayout>
      <PatternLayout
        pattern="%style{%d{ISO8601}}{black} %highlight{%-5level }[%style{%t}{bright,blue}]
        %style{%C{1.}}{bright,yellow}: %msg%n%throwable" />
    </Console>
  </Appenders>
  <Loggers>
    <!-- LOG everything at INFO level -->
    <Root level="info">
      <AppenderRef ref="Console" />
     </Root>
   <Logger name="com.vb" level="trace"></Logger>
 </Loggers>
</Configuration>
Çıktısı şöyle
{
  "thread": "main",
  "level": "INFO",
  "loggerName": "com.vb.math.learnit.LearnitApplication",
  "message": "Started LearnitApplication in 2.508 seconds (JVM running for 4.586)",
  "endOfBatch": false,
  "loggerFqcn": "org.apache.commons.logging.LogAdapter$Log4jLog",
  "instant": {
    "epochSecond": 1597070439,
    "nanoOfSecond": 853000000
  },
  "threadId": 1,
  "threadPriority": 5
}

6 Aralık 2022 Salı

Log4j2 log4j2.xml SMTPLogger Tanımlama

Giriş
Spring kullanıyorsak şu dependency gerekir
<!-- Needed for SMTP appender -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Örnek
Şöyle yaparız. Sadece ERROR seviyesindeki logları e-posta ile gönderir.
<!-- SMTP Appender -->
<SMTP name="MailAppender"
      subject="Log4j2 Demo [PROD]"
      to="youremail@example.com"
      from="log4j2-demo-alerts@example.com"
      smtpHost="yourSMTPHost"
      smtpPort="587"
      smtpUsername="yourSMTPUsername"
      smtpPassword="yourSMTPPassword"
      bufferSize="1">
    <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
    <PatternLayout>
        <Pattern>${LOG_PATTERN}</Pattern>
    </PatternLayout>
</SMTP>




Log4j2 log4j2.xml AsyncLogger Tanımlama

Giriş
Log4j2 async loglama için disruptor kütüphanesini kullanır.

Not : Eğer tüm appender'ları async yapmak istersek sadece yaparız. Eğer bazı appender'ları async yapmak istersek <AsyncLogger> tag içinde belirtmek gerekir.
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
Eğer Spring kullanıyorsak applicatio.properties dosyasında şöyle yaparız
log4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
Maven
Log4j2 kütüphanesine ilave olarak şu satırı dahil ederiz
<!-- Needed for Async Logging with Log4j 2 -->
<dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.3.6</version> </dependency>
Örnek
Şöyle yaparız
<Loggers>

  <AsyncLogger name="com.example.log4j2demo" level="debug" additivity="false">
    <AppenderRef ref="ConsoleAppender" />
    <AppenderRef ref="FileAppender" />
  </AsyncLogger>

  <Root level="info">
    <AppenderRef ref="..." />
    <AppenderRef ref="..." />
  </Root>
</Loggers>


Log4j2 PatternLayout Tanımlama

Giriş
PatternLayout  Appender'lara takılır. Tanımlamak için şöyle yaparız
<PatternLayout pattern="..."/>
veya
<PatternLayout>
  <Pattern>...</Pattern>
</PatternLayout>
Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
  <Properties>
    <Property name="LOG_PATTERN">
      %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
    </Property>
  </Properties>
  ...
</Configuration>

<!-- Rolling File Appender -->
<RollingFile name="FileAppender" fileName="logs/log4j2-demo.log" 
             filePattern="logs/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
  <PatternLayout>
    <Pattern>${LOG_PATTERN}</Pattern>
  </PatternLayout>
  <Policies>
    <SizeBasedTriggeringPolicy size="10MB" />
  </Policies>
  <DefaultRolloverStrategy max="10"/>
</RollingFile>
Örnek
Şöyle yaparız
<Configuration status="DEBUG">
  <Appenders>
    <Console name="LogToConsole" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
    <RollingRandomAccessFile ...">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
      ...
  </Appenders>
  <Loggers>
    ...           
  </Loggers>
</Configuration>
%d
DateTime anlamına gelir. İstenirse format belirtilir.
Örnek
Şöyle yaparız
%d{HH:mm:ss.SSS}
Örnek
Şöyle yaparız
%d{ISO8601}
%level
Level bilgisini gösterir.
Örnek
Şöyle yaparız
%-5level
%logger
Logger ismini gösterir
Örnek
Şöyle yaparız
%logger{36}

31 Ekim 2021 Pazar

Log4j2 log4j2.xml RollingFile Tanımlama

Giriş
Policy olarak SizeBasedTriggeringPolicy veya TimeBasedTriggeringPolicy kullanılabilir.

OnStartupTriggeringPolicy 
Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Liquid Technologies Online Tools 1.0 (https://www.liquid-technologies.com) -->
<Configuration status="WARN"
               monitorInterval="30"
               shutdownHook="disable">
  <Properties>
    <Property name="baseDir">$${env:HOME}/logs</Property>
    <Property name="applicationName">my-application</Property>
  </Properties>
  <Appenders>
    <RollingFile
       name="RollingFile"
       fileName="${baseDir}/${applicationName}.log"
       filePattern="${baseDir}/${applicationName}.%d{yyyy-MM-dd}-%i.log">
      <PatternLayout pattern="%-5p|%d{ISO8601}{GMT}|%X{token}|%c{1}|%X{Principal}|%m%ex%n" />
      <Policies>
        <OnStartupTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="20 MB" />
        <TimeBasedTriggeringPolicy />
      </Policies>
      <DefaultRolloverStrategy max="10">
        <Delete basePath="${baseDir}">
          <IfFileName glob="${applicationName}.*.log">
            <IfAny>
              <IfAccumulatedFileSize exceeds="200 MB" />
              <IfAccumulatedFileCount exceeds="10" />
            </IfAny>
          </IfFileName>
        </Delete>
      </DefaultRolloverStrategy>
      <RegexFilter regex=".*@ConfigurationProperties.*"
                   onMatch="DENY"
                   onMismatch="ACCEPT" />
    </RollingFile>
   
  </Appenders>
  <Loggers>
    <Root level="WARN">
      <AppenderRef ref="RollingFile" />
       </Root>
    <Logger name="org.springframework"
            level="WARN" />
    <Logger name="com.my.app"
            level="INFO" />
  </Loggers>
</Configuration>

TimeBasedTriggeringPolicy 
Örnek
Şöyle yaparız. interval gün cinsinden. Her gün dosyayı değiştirir.  Eğer her hafta yapmak isteseydik interval="7" yaparız
<Policies>
    <TimeBasedTriggeringPolicy interval="1" />
</Policies>

SizeBasedTriggeringPolicy 
Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN" monitorInterval="30"> <Properties> <Property name="LOG_PATTERN"> %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex </Property> </Properties> ... </Configuration> <!-- Rolling File Appender --> <RollingFile name="FileAppender" fileName="logs/log4j2-demo.log" filePattern="logs/log4j2-demo-%d{yyyy-MM-dd}-%i.log"> <PatternLayout> <Pattern>${LOG_PATTERN}</Pattern> </PatternLayout> <Policies> <SizeBasedTriggeringPolicy size="10MB" /> </Policies> <DefaultRolloverStrategy max="10"/> </RollingFile>
Örnek
Şöyle yaparız
<Appenders>
  <RollingFile name="file" 
    fileName="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}log.log"
    filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}log-%i.log">
    <PatternLayout pattern="%-5p %d [%t] [%MDC] %c: %m%n"/>
    <SizeBasedTriggeringPolicy size="10 MB"/>
    <DefaultRolloverStrategy max="10"/>
  </RollingFile>
</Appenders>