Logging is working fine if i specify
'logging.config = src/main/resources/log4j2.properties'
in my application.properties file.
Is there any other work around where spring boot automatically detects log4j2.properties and doesnot require to specify 'logging.config = src/main/resources/log4j2.properties' inside application.properties file..?
Spring Boot automatically detects log4j2.xml, log4j2.json files in classpath, but not in case log4j2.properties file, in my case
my pom.xml:
<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>
log4j2.properties:
name=PropertiesConfig
appenders = console, file
appender.console.type = Console
appender.console.name = ConsoleAppender
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{MM:dd HH:mm:ss.SSS} [%t]
[%level] [%logger{36}] - %msg%n
appender.file.type = File
appender.file.name = FileAppender
appender.file.fileName=/home/ubuntu/application.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern= %d{MM:dd HH:mm:ss.SSS} [%t] [%level]
[%logger{36}] - %msg%n
loggers=file
logger.file.name=com.project
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = FileAppender
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = ConsoleAppender
Note : Spring boot version i am using is 2.1.3.RELEASE
Reference : https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html
I am not aware that Spring Boot modifies the logic Log4j 2 uses to locate configuration files. In fact, I have been working on a Spring Boot service that was using a log4j2.yml. I replaced that with a log4j2.properties and it worked fine. Log4j's normal discovery process finds it on the class path.
I am actually surprised that specifying logging.config=src/main/resources/log4j2.properties worked for you as a Spring Boot jar wouldn't normally have the "src" directory in it.
also can use this way:
java -Dlog4j.configurationFile=log4j2.xml -jar xxxx-app.jar
Reference:
https://logging.apache.org/log4j/2.x/manual/configuration.html
Related
For some reason, my log4j configuration file is getting ignored.
The configuration is file found in
C:\dev\pa-backup-restore-utility\BackupRestore\log4j2.properties
Here are the contents of the file:
name=PropertiesConfig
property.filename = logs
appenders = console, file
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=logs/backupRestore.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
loggers=file
logger.file.name=log4j2.properties
logger.file.level = error
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE
rootLogger.level = error
rootLogger.appenderRefs=stdout,logfile
rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.appenderRef.logfile.ref=LOGFILE
The batch file that runs the class is located in the same directory as the configuration file.
The command from the batch file is run as follows:
set javaPath="%appDir%\jre\bin\java.exe"
%javaPath% -Dapp.properties.path=windows.app.properties -Dlog4j.configurationFile=file:log4j2.properties -jar backupRestore-jar-with-dependencies.jar -b
The entry in pom.xml for this is:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.16.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
</dependency>
Here's how a logger.info is called:
static void printWarning(String message) {
logger.info("============== warning ===============================");
logger.info("== " + message);
logger.info("============== warning ===============================");
}
However, when I run the batch job, an info message gets displayed in the console:
[main] INFO com.sick.backup.util.Utils - ============== warning ===============================
[main] INFO com.sick.backup.util.Utils - == here is an example message
[main] INFO com.sick.backup.util.Utils - ============== warning ===============================
Also, a log file is no longer getting generated.
This was all working at what point. I'm trying to track down the version to make sure it matches, but the only change I've made is to upgrade the version of log4j-to-slf4j due to prevent a vulnerability.
My configuration file is path of the class path. At least I thought it is. I placed the log4j.properties file in the resources folder and log4j does nothing with it. Even if I delete it, no error occurs.
As anyone can see I'm using maven
Content of LoggerTest:
package com.dersimi.stella.logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoggerTest {
public static void main(String[] args) {
System.out.println("xxx");
Logger logger = LogManager.getLogger(LoggerTest.class);
logger.info("Hello this is an info message");
System.out.println("xxx");
}
}
Program output:
xxx
xxx
Content of log4j.properties:
log4j.rootLogger=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
In pom.xml is nothing out of the ordinary, just the dependency org.apache.logging.log4j log4j-core 2.17.2, compiler source target is 16, no plugins
The main problem is that you are trying to use log4j (the first one) configurations for log4j2.
In first place make sure you have the following dependencies:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.0</version>
</dependency>
Second, have a file named log4j2.properties with a content like this:
status = warn
appender.console.type = Console
appender.console.name = LogToConsole
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = LogToConsole
Reference: https://mkyong.com/logging/log4j2-properties-example/
I'm trying to use the slf4j-Logger-Functions but always getting the same error:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for
further details.
I already tried the common solutions and as you can see in the image, the "StaticLoggerBinder" is loaded into the directory but the error still excists. Do you have any idea why?
package de.stefan.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Test.class);
logger.info("This is how you configure Java Logging with SLF4J");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.stefan</groupId>
<artifactId>stefan</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
</project>
Project structure
slf4j-simple is not your classpath when you ran the program. Put it in your classpath, something like java -classpath ./lib/* YourProgram. Where lib contains your jar files.
Just make sure you have following 4j dependencies in pom, and add log4j.properties/xml with required appanders i.e. for Console or/and file in your class path .
Mention the the version in properties as per your needs, recent is better-
<log4j.version>2.13.3</log4j.version>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
A sample Log4j Config Properties file can be like this-
status = error
name= properties_configuration
# Give directory path where log files should get stored
#property.basePath = E:\\AppTest_logs\\
# ConsoleAppender will print logs on console
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
appender.file.type = File
appender.file.name = STDOUT
appender.file.filename = logs/AppsConsole.log
appender.file.layout.type = PatternLayout
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = error
# Specify the pattern of the logs
appender.console.layout.pattern = %highlight{ [%p] %d{dd MMM yyyy HH:mm:ss,SSS} [%t] %x %c %M - %m%n}{FATAL=white, ERROR=Blink red, WARN=Underline yellow, INFO=Bright white, DEBUG=Bright green, TRACE=blue}
appender.file.layout.pattern = %d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n
# RollingFileAppender will print logs in file which can be rotated based on time or size
# Mention package name here in place of example. Classes in this package or subpackages will use ConsoleAppender and RollingFileAppender for logging
logger.example.name = com.threeylos.zapizook
logger.example.level = info
logger.example.additivity = false
logger.example.appenderRef.rolling.ref = fileLogger
logger.example.appenderRef.console.ref = consoleLogger
# Configure root logger for logging error logs in classes which are in package other than above specified package
rootLogger.level = info
rootLogger.additivity = false
#rootLogger.appenderRef.rolling.ref = fileLogger
rootLogger.appenderRef.console.ref = consoleLogger
I'm using an external JAR library that creates a log file every time is used:
private void initLogger() {
try {
boolean var1 = true;
FileHandler var2 = new FileHandler("lib.log", 4096000, 1, var1);
var2.setFormatter(new SimpleFormatter());
this.logger = Logger.getLogger("POS");
this.logger.addHandler(var2);
} catch (IOException var3) {
var3.printStackTrace();
}
}
This, create the files lib.log , lib.log.lck, etc...
The problem is that my App is using log4j(from maven xml):
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
What I want is simple, I want to redirect all the calls of that lib log to my logger.
I've tried using jul-to-slf4j :
https://www.slf4j.org/legacy.html
<!-- https://mvnrepository.com/artifact/org.slf4j/jul-to-slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
With this configuration (console + daily file):
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1, RollingAppender
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%-5p] %d %c - %m%n
log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingAppender.File=pos.log
log4j.appender.RollingAppender.DatePattern='.'yyyy-MM-dd
log4j.appender.RollingAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingAppender.layout.ConversionPattern=[%-5p] %d %c - %m%n
And then put this code at the beginning:
LogManager.getLogManager().reset();
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
Logger.getLogger("POS").setLevel(FINEST);
With this, the file is created (lib.log) but it's empty. And the output doesn't go to pos.log ( the one configured in log4j).
What I'm missing? Thanks!
You did not include slf4j-log4j12 in your project (more).
Maybe Log4j JDK Logging Adapter is better solution.
I am creating a Spring Boot Application in STS (Spring Tool Suite).
The problem occurs when trying to log using log4j. It does not create the log file in the system, though it does log on the console. I tried various methods given in the forum(including checking case-sensitivity, , but I think I am going wrong somewhere. An elaborate response would be really helpful.
I have a dependency in the pom.xml file for the log4j jar:-
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
In my log4j.properties file, I am trying to have logs in console as well as a file
# Root logger option
log4j.rootLogger=ALL, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\log4j.log
log4j.appender.file.ImmediateFlush=true
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.FILE.layout.conversionPattern=%m%n
log4j.appender.file.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Java controller where I want to log (IndexController.java)
package com.project.Controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class IndexController {
final static Logger logger = Logger.getLogger(IndexController.class.getName());
#RequestMapping("/")
String index(Model model) {
logger.info("in index");
return "index";
}
}
Please comment if you need any further details. Thanks
Create a dependency for spring-boot-starter-log4j and exclude spring-boot-starter-logging in your pom.xml.Make the following entry in your pom.xml:
<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-log4j</artifactId>
</dependency>
This should create the log file and log the details.