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

27 Kasım 2022 Pazar

SpringBootLogging application.properties - Basit logging Ayarları

Giriş
Basit loglama ayarlarını belirtmek için application.properties kullanır. Daha karmaşık şeyler için logback.xml kullanılabilir. Açıklaması şöyle
If you need to apply customizations to logback beyond those that can be achieved with application.properties, you’ll need to add a standard logback configuration file. You can add a logback.xml file to the root of your classpath for logback to find. You can also use logback-spring.xml if you want to use the Spring Boot Logback extensions.
Örneğin rolling file appender kullanmayı ben bulamadım bu yüzden logback.xml dosyasını src/main/resources altına ekledim.

Varsayılan Log Formatı
Açıklaması şöyle. Yani varsayılan çıktıda her satırda toplam 7 tane şey var.
Spring Boot preconfigures it with patterns and ANSI colors to make the standard output more readable.

The default log output from Spring Boot resembles the following example:

The following items are output:

I. Date and Time: Millisecond precision and easily sortable.
II. Log Level: ERROR, WARN, INFO, DEBUG, or TRACE.
III. Process ID.
IV. A — — separator to distinguish the start of actual log messages.
V. Thread name: Enclosed in square brackets (may be truncated for console output).
VI. Logger name: This is usually the source class name (often abbreviated).
VII. The log message.

The following table describes the mapping of log levels to colors: Level Color

FATAL: Red
ERROR: Red
WARN: Yellow
INFO: Green
DEBUG: Green
TRACE: Green
logging.pattern.console ve logging.pattern.file kullanılır

Örnek - Log Format Customization
Şöyle yaparız
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n
Açıklaması şöyle
This pattern includes the timestamp, logger name (up to 36 characters), and the actual message.

logging.file Alanı - Log Dosyasının Yolu
Örnek
Şöyle yaparız
logging.file.path=.
Örnek
Şöyle yaparız
logging.file=/home/ubuntu/spring-boot-app.log
Örnek
Şöyle yaparız
logging.file.name=myapp.log
Örnek - Log File Rotation
Şöyle yaparız
logging.file.max-size=10MB
logging.file.max-history=10
logging.level Alanı 
Örnek - Root Loglama Seviyesini Ayarlamak
Şöyle yaparız
logging.level.root=DEBUG
Örnek - Loglama Patern'i Değiştirmek
Şöyle yaparız.
logging.level.root=info
logging.path=path
logging.file=${logging.path}/log.log
logging.pattern.file=
  %d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
logging.pattern.console=
  %d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %n%highlight%msg%n
Spring Data Sınıfları
Örnek
Spring data sınıflarının loglama seviyesi için şöyle yaparız.
#logging
logging.level.org.springframework.data=debug
logging.level.=error
Örnek
Şöyle yaparız.
logging.level.org.springframework.security=ERROR
logging.level.com.test=DEBUG
Spring Web Sınıfları
Şöyle yaparız
logging.level.org.springframework.web=INFO

15 Eylül 2022 Perşembe

SpringBootLogging logback-spring.xml - Spring Boot Logback Extensions Kullanır

Giriş
Spring'e özel bazı tag'ların kullanılması mümkün.

Include ile şunlar dahil edilebilir. Bazı hazır appender'lar kullanılabiliyor.
org/springframework/boot/logging/logback/defaults.xml
org/springframework/boot/logging/logback/console-appender.xml
org/springframework/boot/logging/logback/file-appender.xml

Örnek
Eğer SpringBoot içinde çıkan ayarları kullanmak ancak bazı özelleştirmeler yapmak istersek şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!—Include the base xmls with all configurations in place -->
  <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
  <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
  <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
  <!—Override the required values -->
  <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
  <root level="INFO">
   <appender-ref ref="CONSOLE" />
   <appender-ref ref="FILE" />
  </root>
  <logger name="org.springframework.web" level="DEBUG"/>
</configuration>
springProfile Tag
Açıklaması şöyle
... there are also some logical operands that you can use to have a combinational or exceptional configuration. “|” will let you simulate “OR” and “!” will mimic the exception.
Örnek
Şöyle yaparız
<springProfile name="prod">
<!-- enabled when the "prod" profile is active --> </springProfile> <springProfile name="dev | test"> <!-- enabled when the "dev" or "test" profiles are active --> </springProfile> <springProfile name="!prod"> <!-- enabled when the "prod" profile is not active --> </springProfile>
Örnek
Şöyle yaparız
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <encoder>
    <pattern>${FILE_LOG_PATTERN}</pattern>
  </encoder>
  <file>temp/spring.log</file>
  <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"
  <fileNamePattern>temp/spring.log.%d</fileNamePattern>   
  </rollingPolicy>
</appender>
<springProfile name="test | dev">  
   <logger name="fp.spring" level="DEBUG" additivity="false">
       <appender-ref ref="CONSOLE" />
   </logger>
   <root level="DEBUG">
      <appender-ref ref="CONSOLE" />
      <appender-ref ref="FILE" />
   </root>
</springProfile>
<springProfile name="prod">
    <root level="INFO">
      <appender-ref ref="FILE" />
    </root>
</springProfile>
</configuration>
Örnek - profile
Şöyle yaparız. Burada spring profile değerine göre farklı property'ler atanıyor. Propertylere ${...} şeklinde erişiliyor
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- Use Spring default values. -->
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <springProfile name="default | local">
        <property name="LOGS_FOLDER" value="./logs"/>
        <property name="FILE_PATH" value="${LOGS_FOLDER}/java-aws-rnd-logging-local.log"/>
    </springProfile>

    <springProfile name="dev | uat | prod">
        <property name="LOGS_FOLDER" value="/home/ec2-user/java-aws-rnd/logs"/>
    </springProfile>

    <springProfile name="uat">
        <property name="FILE_PATH" value="${LOGS_FOLDER}/java-aws-rnd-logging-uat.log"/>
    </springProfile>

    <springProfile name="prod">
        <property name="FILE_PATH" value="${LOGS_FOLDER}/java-aws-rnd-logging-prod.log"/>
    </springProfile>

    <springProfile name="dev">
        <property name="FILE_PATH" value="${LOGS_FOLDER}/java-aws-rnd-logging-dev.log"/>
    </springProfile>

    <property name="MAX_FILE_SIZE" value="1MB"/>
    <property name="TOTAL_SIZE_CAP" value="1GB"/>
    <property name="MAX_HISTORY" value="60"/>


    <property name="ROLLING_POLICY_LOG_FILE_PATTERN" value="${FILE_PATH}.%d{yyyy-MM-dd}.%i.gz"/>
    <property name="CONSOLE_LOG_PATTERN"
              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5level) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %X{userId} %m%n%wEx"/>
    <property name="FILE_LOG_PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5level ${PID:- } --- [%15.15t] %-40.40logger{39} : %X{userId} %m%n%wEx"/>

    <appender name="Console"
              class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </layout>
    </appender>

    <appender name="RollingFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${FILE_PATH}</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${ROLLING_POLICY_LOG_FILE_PATTERN}</fileNamePattern>
            <maxFileSize>${MAX_FILE_SIZE}</maxFileSize>

            <!--
                Controls the total size of all archive files. Oldest archives are deleted asynchronously when the total size cap is exceeded.
                The totalSizeCap property requires maxHistory property to be set as well. Moreover,
                the "max history" restriction is always applied first and the "total size cap" restriction applied second.
            -->
            <totalSizeCap>${TOTAL_SIZE_CAP}</totalSizeCap>

            <!--
                Controls the maximum number of archive files to keep,
                asynchronously deleting older files. For example, if you specify monthly rollover, and set maxHistory to 6,
                then 6 months worth of archives files will be kept with files older than 6 months deleted.
                Note as old archived log files are removed, any folders which were created for the purpose of log
                file archiving will be removed as appropriate.
            -->
            <maxHistory>${MAX_HISTORY}</maxHistory>

            <!--
                The optional maxHistory property controls the maximum number of archive files to keep, asynchronously deleting older files.
                For example, if you specify monthly rollover, and set maxHistory to 6, then 6 months worth of archives files will be kept
                with files older than 6 months deleted. Note as old archived log files are removed, any folders which were created for the
                purpose of log file archiving will be removed as appropriate.
            -->
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
    </appender>

    <!-- LOG everything at INFO level -->
    <root level="info">
        <springProfile name="default | local">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFile"/>
        </springProfile>

        <springProfile name="dev | uat | prod">
            <appender-ref ref="RollingFile"/>
        </springProfile>
    </root>
</configuration>

27 Temmuz 2021 Salı

SpringBootLogging Log4J2 Kullanımı

Giriş
SpringBoot loglama için normalde logback kullanır. Açıklaması şöyle
If your spring boot project has been created from the starters project (which almost always is the case), it would have a transitive dependency on spring-boot-starter-logging, and you would not need to include any additional dependency to start with logging in your app. The default choice of framework that spring boot makes is Logback and Slf4j.
SpringBoot logging Ayarları yazısına bakabilirsiniz.

Log4J2 kullanmak için logback veya herhangi bir başka logger'ın path içinde olmaması lazım. Mesela lombok kütüphanesi slf4j kullanıyor.

Örnek
Şöyle yaparız
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Örnek
Şöyle yaparız
</dependency><dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <exclusions>
    <exclusion>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
    <exclusion>
     <groupId>ch.qos.logback</groupId>
     <artifactId>logback-classic</artifactId>
    </exclusion>
   </exclusions>
</dependency>
Log4J Konfigürasyon Dosyası
Açıklaması şöyle. Yani XML, JSON veya YAML dosyası kullanılabilir. src/main/resources altına yerleştirilebilir.
Spring Boot automatically configures Log4j if it finds a file named log4j2.xml or log4j2.json or log4j2.yaml in the classpath.

log4j2.xml Dosyası
xml dosyasını yine logback kullanımında olduğu gibi src/main/resources/log4j2.xml şeklinde yaratırız. 

Spring Profile
Açıklaması şöyle
The <SpringProfile> tag lets you include custom configuration based on the active Spring profiles. 
Örnek
Şöyle yaparız
<SpringProfile name=”dev | test”>
<! — configuration to be enabled when the “dev” or “test” profiles are active →
</SpringProfile>

<SpringProfile name=”staging”>
<! — configuration to be enabled when the “staging” profile is active →
</SpringProfile>

<SpringProfile name=”!production”>
<! — configuration to be enabled when the “production” profile is not active →
</SpringProfile>
Örnek
Şöyle yaparız. Burada dev ve prod diye iki profile var
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="logback-spring.xsd">

 <springProfile name="dev">
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
   <encoder>
    <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
   </encoder>
  </appender>
  <logger name="com.springboot.postgres" level="debug">
   <appender-ref ref="console" />
  </logger>
 </springProfile>

 <springProfile name="prod">
  <appender name="file" class="ch.qos.logback.core.FileAppender">
   <file>app.log</file>
   <encoder>
    <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
   </encoder>
  </appender>
  <logger name="com.springboot.postgres" level="info">
   <appender-ref ref="file" />
  </logger>
 </springProfile>

</configuration>
Environment Properties Kullanımı
Açıklaması şöyle
You can look up properties from Spring Environment within your Log4j2 configuration. For instance, if configure the spring.application.name property in application.properties file, you can use it in your Log4j2 xml configuration with the following configuration. We are using the spring: prefix.
Örnek
Şöyle yaparız
<Properties> 
  <Property name=”applicationName”>${spring:spring.application.name}</property> 
</Properties>
Örnek
Şöyle yaparız. Burada logging.level ortam değişkeni kullanılıyor. Eğer tanımlı değilse varsayılan değer debug
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="logback-spring.xsd">

 <springProfile name="dev">
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
   <encoder>
    <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
   </encoder>
  </appender>
  <logger name="com.springboot.postgres" level="${logging.level:-debug}">
   <appender-ref ref="console" />
  </logger>
 </springProfile>
</configuration>
System Properties Kullanımı
Örnek
Şöyle yaparız. Burada sys:logging.level isimli system properties değişkeni kullanılıyor. Eğer tanımlı değilse varsayılan değer debug
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="logback-spring.xsd">

 <springProfile name="dev">
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
   <encoder>
    <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
   </encoder>
  </appender>
  <logger name="com.springboot.postgres" level="${sys:logging.level:-debug}">
   <appender-ref ref="console" />
  </logger>
 </springProfile>
</configuration>