Log4j is not logging into file or console - java

I am trying to learn log4j version 2.x. The log4j properties are done using xml. The code given below is in a maven project in eclipse STS. It does not print any logging messages into the console or file.
I don't know how to debug this. Googling did not give me any answers for eclipse. Please suggest how I can debug this myself and fix it. I don't need full answer right away, unless most/all of my code is wrong.
Code:
package com.api.log4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoggingExample {
static Logger logger = LogManager.getLogger(LoggingExample.class);
private void loggerLevel(String message) {
if (logger.isDebugEnabled()) {
logger.debug("This is set to debug: " + message);
}
if (logger.isInfoEnabled()) {
logger.info("This is set to info: " + message);
}
logger.warn("This is set to warn: " + message);
logger.error("This is set to error: " + message);
logger.fatal("This is set to fatal: " + message);
}
public static void main(String[] args) {
System.out.println("Running main...");
LoggingExample loggingExample = new LoggingExample();
loggingExample.loggerLevel("calling the loggerLevel method...");
}
}
Log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="System.out">
<PatternLayout>
[%-5level]<!-- Use 5 chars to show the level text. If level text < 5
chars, then append spaces to make it 5 chars. -->
%d{yyyy-MM-dd HH:mm:ss.SSS}<!-- The date. -->
[%t]<!-- Which thread is running. -->
%c{1}<!-- Class being logged. -->
- %msg%n
</PatternLayout>
</Console>
<File name="File" filename="/src/main/resources/log4j-file.txt">
<PatternLayout>
[%-5level]<!-- Use 5 chars to show the level text. If level text < 5
chars, then append spaces to make it 5 chars. -->
%d{yyyy-MM-dd HH:mm:ss.SSS}<!-- The date. -->
[%t]<!-- Which thread is running. -->
%c{1}<!-- Class being logged. -->
- %msg%n
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root>
<AppenderRef ref="Console" /> <!-- Appends only to console appender -->
</Root>
<Logger name="com.api.log4j.LoggingExample" level="debug"
additivity="false">
<AppenderRef ref="File" /> <!-- Appends only to file appender -->
</Logger>
</Loggers>
</Configuration>

1.If you are using MAVEN build tools make sure log4j.jar is added to your lib folder.
2.Write your configuration parameter in log4j.properties file and your log will work !!
# Root logger option
log4j.rootLogger=DEBUG,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=your File path
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout

Related

Log4j2.xml configuration doesn't work but log4j2.properties does

Hello I have this problem were if i use a log4j2.xml file as a configuration file the logger won't log to console, whereas if i am using a .properties file instead i will have the logs in file.
This is the .xml file
<?xml version="1.0" encoding="UTF-8"?>
<!-- Extra logging related to initialization of Log4j.
Set to debug or trace if log4j initialization is failing. -->
<Configuration status="warn">
<Appenders>
<!-- Console appender configuration -->
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</Console>
</Appenders>
<Loggers>
<!-- Root logger referring to console appender -->
<Root level="info" additivity="false">
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>
.properties file:
# Set to debug or trace if log4j initialization is failing
status = warn
# Name of the configuration
name = ConsoleLogConfigDemo
# Console appender configuration
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Root logger level
rootLogger.level = debug
# Root logger referring to console appender
rootLogger.appenderRef.stdout.ref = consoleLogger
(I am trying to do this for a migration from log4j to log4j2 and if i am using the .properties file everything seems to work)
I had the properties file and xml file both in resources folder.

Need to append params to each and every log before - in log4j in java

I need to append my variables to my logger for each and every log.
Has to update the configuration log4J file to update the print statements for every log output. This information should be at the beginning of every log statement.
If you look at one of the log outputs :
"2018-02-02 15:34:43 INFO TestClass:135 - Start time stamp is: 1517585580000 and HHmm is: 1533"
I need to edit the part before the "-"
i.e., 1533 param1 Param2 timestamp 2018-02-02 15:34:43 INFO TestClass:135 - - Start time stamp is: 1517585580000 and HHmm is: 1533.
Note: the params vary from log to log i can pass them in through logger.info.
Can anyone help me on this?
By using ThreadContext and pattern in log4j2.xml or log4j2.properties file in got expected output. Please find the below piece of code.
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<!-- Console Appender -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %X{param1} %X{param2} %X{param3} - %m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
or
log4j2.properties
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Direct log messages to stdout
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 %X{param1} %X{param2} %X{param3} - %m%n
And
In JAVA file
package com.test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
public class Test {
public static void ThreadContextLoggerCreation(long param1, String param2, String param3) {
ThreadContext.push(UUID.randomUUID().toString()); // Add the fishtag;
ThreadContext.put("param1", param1);
ThreadContext.put("param2", param2);
ThreadContext.put("param3", param3);
ThreadContext.pop();
}
public static void ThreadContextLoggerClear() {
ThreadContext.clearAll();
}
public static void main(String args[]) {
Logger logger = LogManager.getLogger(Test.class);
LogUtil.ThreadContextLoggerCreation(logger, currentTime, customerId, agentLocation, streamId, streamVariant, levelOfDetail);
logger.info("Current Time of execution(HHmm) is: {}", BatchTimeUtil.convertTimestampToReadableDate(currentTime));
}
}
You are perhaps looking for custom layout. Below articles should help you. In a nutshell, create a custom layout, set up your own conversion characters and handle the log message (& object var args) accordingly to replace conversion characters with appropriate dynamic values.
http://www.wideskills.com/log4j-tutorial/10-custom-appender-and-layout-in-log4j
https://fw-geekycoder.blogspot.in/2010/07/creating-log4j-custom-patternlayout.html
OR
You can try MDC/ThreadContext in log4j/log4j2 for that matter. This will allow you to supply dynamic piece of log information by means of a simple Map & have that available in your log layout using custom patterns strings. Please take a look at below article in this regard -
http://www.baeldung.com/mdc-in-log4j-2-logback

How configure SLF4J underlying configuration file location [duplicate]

I have the followed imports:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
and the following instantiation:
private static Logger logger = LoggerFactory.getLogger(Test.class);
and the following in my Main method:
logger.info("SOME MESSAGE: ");
However, I'm not able to find the output anywhere. All I see is that in my console there is:
21:21:24.235 [main] INFO some_folder.Test - SOME MESSAGE:
How do I locate the log file?
Note that the following are on my build path:
slf4j-api-1.7.5.jar
slf4j-log4j12-1.6.4.jar
I read the answer to similar questions but nobody actually says how to fix the problem.
slf4j is only an API. You should have a concrete implementation (for example log4j). This concrete implementation has a config file which tells you where to store the logs.
When slf4j catches a log messages with a logger, it is given to an appender which decides what to do with the message. By default, the ConsoleAppender displays the message in the console.
The default configuration file is :
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<!-- By default => console -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
If you put a configuration file available in the classpath, then your concrete implementation (in your case, log4j) will find and use it. See Log4J documentation.
Example of file appender :
<Appenders>
<File name="File" fileName="${filename}">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
...
</Appenders>
Complete example with a file appender :
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="File" fileName="${filename}">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
As already mentioned its just a facade and it helps to switch between different logger implementation easily. For example if you want to use log4j implementation.
A sample code would looks like below.
If you use maven get the dependencies
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
Have the below in log4j.properties in location src/main/resources/log4j.properties
log4j.rootLogger=DEBUG, STDOUT, file
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=mylogs.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n
Hello world code below would prints in console and to a log file as per above configuration.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml

log4j2 configuration with disruptor

I am trying to use log4j2 with disruptor in a java application. I have the following jar files in my classpath:
log4j-api-2.0-rc2.jar
log4j-core-2.0-rc2.jar
disruptor-3.2.0.jar
In my Java class, I a doing the following to test:
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class LoggerTest {
private static final Logger Logger = LogManager.getLogger(LoggerTest.class.getName());
public static void main(String[] args) {
Logger.info("testing log4j2 with disruptor");
}
My log4j2.xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Don't forget to set system property
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
to make all loggers asynchronous. -->
<configuration status="INFO">
<appenders>
<!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
<FastFile name="RandomAccessFile" fileName="logs/test.log" immediateFlush="false" append="false">
<PatternLayout>
<pattern>%d %p %c{1.} [%t] %m %ex%n</pattern>
</PatternLayout>
</FastFile>
</appenders>
<loggers>
<root level="info" includeLocation="true">
<appender-ref ref="RandomAccessFile"/>
</root>
</loggers>
</configuration>
When I run the application, I get the following error (with no log output):
2014-07-10 14:45:32,930 ERROR Error processing element FastFile: CLASS_NOT_FOUND
2014-07-10 14:45:32,973 ERROR Unable to locate appender RandomAccessFile for logger
In beta9, the <FastFile> appender was renamed to <RandomAccessFile>. If you rename this element in your configuration it should work.

Log4j 2.0 - No Logs appearing in the Log Files - Trying Multiple Loggers in the same Class using log4j2.xml

Below is the log4j2.xml file that I have created. I have configured async_file.log for Asynchronous Logging and regular_file.log for regular and synchronous logging. The problem is that the log files get created, but the size of the files is zero and with no logs. All logs are coming to server.log file (JBOSS) and not to the 2 files that I had got configured for (async_file.log and regular_file.log).
Please let me know why the logs are NOT going to the log files that I have configured. Please help me with this or give me some direction or hint.
I am calling the two different loggers in the same class file by name DCLASS as shown below:
private static final transient Logger LOG = Logger.getLogger(DCLASS.class);
private static final transient Logger ASYNC_LOG = Logger.getLogger("ASYNC");
I have included the following jars in the Class Path:
1. log4j-api-2.0-beta8.jar
2. log4j-core-2.0-beta8.jar
3. disruptor-3.0.0.beta1.jar
My log4j2.xml is as below:
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="INFO">
<appenders>
<!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
<FastFile name="AsyncFastFile" fileName="../standalone/log/async_file.log"
immediateFlush="false" append="true">
<PatternLayout>
<pattern>%d %p %class{1.} [%t] %location %m %ex%n</pattern>
</PatternLayout>
</FastFile>
<FastFile name="FastFile" fileName="../standalone/log/regular_file.log"
immediateFlush="true" append="true">
<PatternLayout>
<pattern>%d %p %class{1.} [%t] %location %m %ex%n</pattern>
</PatternLayout>
</FastFile>
</appenders>
<loggers>
<!-- pattern layout actually uses location, so we need to include it -->
<asyncLogger name="ASYNC" level="trace" includeLocation="true">
<appender-ref ref="AsyncFastFile"/>
</asyncLogger>
<root level="info" includeLocation="true">
<appender-ref ref="FastFile"/>
</root>
</loggers>
</configuration>
The reason why the logs were not coming to the log files is because, I was using 'Logger' instead of 'LogManager'.
In the code, I had
private static final transient Logger ASYNC_LOG = Logger.getLogger("ASYNC");
The code should have been
private static final transient Logger ASYNC_LOG = Logmanager.getLogger("ASYNC");
When it is 'logger', then the compiler is looking into 'Log4j API' and when it is 'LogManager' it is looking into 'Log4j2 API'. Since I have configured everything to use Log4j2, by changing logger to LogManager, the logs started coming to the log files as expected.

Categories

Resources