I am trying to set up log4j in a simple Java project. I keep getting the following message when running my project.
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
However I have added log4j.xml to my classpath. For example am I doing this in my main method:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLClassLoader;
public class main {
private static Logger logger = LogManager.getLogger("Test");
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public static void main(String [] args) {
InputStream cl = ClassLoader.getSystemClassLoader().getResourceAsStream("log4j.xml");
System.out.println(convertStreamToString(cl));
}
}
When I execute this code I get the contents of my log4j.xml file, which would make it seem the the file is being loaded onto my class path properly?
Here is the content of my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.foo.Bar" level="trace">
<AppenderRef ref="Console"/>
</Logger>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Any ideas on what I am doing wrong?
Change the file name of log4j.xml to log4j2.xml.
I hope it helps.
Related
I wrote a simple program in which I am using Logback. My intention was to use ASYNS which internally will use STDOUT.
Here is the Java code listing:
package com.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogBackMainApp {
private static final Logger LOGGER =
LoggerFactory.getLogger(LogBackMainApp.class);
public static void main(String[] args) throws InterruptedException {
LOGGER.info("Hello world");
LOGGER.info("Hello world again");
Thread.sleep(5000);
}
}
The below is the configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" >
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- %d{yyyy-MM-dd HH:mm:ss.SSS} %thread %-5level %logger{0}:%L
If you required class name ,enable %logger{0}:%L -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %thread %-5level - %msg
%n</pattern>
</encoder>
</appender>
<appender name="ASYNC-STDOUT" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>1</queueSize>
<discardingThreshold>20</discardingThreshold>
<neverBlock>true</neverBlock>
<appender-ref ref="STDOUT" />
</appender>
<root level="INFO">
<appender-ref ref="ASYNC-STDOUT" />
</root>
I am defining root logger which would cater to my com.example package, and it refers to ASYNC-STDOUT, which internally uses ch.qos.logback.core.ConsoleAppender.
As per my current understanding, it should be able to log to console. However, nothing is coming. Is there something wrong in my code or configuration OR do i miss to understand the concept altogether.
If you use maven have a look: Dependency management for SLF4J and Logback. Maybe you're missing a required dependency. Sl4j is only an abstraction for you're real logger implementation which has to be added as dependency.
Log4j is finding my config, because as soon as I delete it I get an error message saying it couldn't find one, however it's properties are not reflected when logging.
log4j2.properties:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Test.java:
public class Test {
private static Logger logger = LogManager.getLogger(Test.class);
public static void main(String[] args) throws Exception {
logger.info("test");
logger.fatal(logger.getLevel());
}
}
Output:
20:19:31.848 [main] FATAL io.rj93.sarcasm.examples.CnnSentenceClassificationExample - ERROR
As you can see, the logger is returning the level to be ERROR when it is set to INFO, and the time format is including the milliseconds even though it has been removed.
The config file is taken from the log4j website, with only minor changes (the two mentioned, and status="TRACE")
I am using version 2.8.1.
You use a log4j2.properties file with a XML configuration inside it.
It is not consistent.
The log4J initialization doesn't recognize the format used as a properties format. So it uses the default log4J configuration that specifies ERROR level for the root logger.
Simply rename log4j2.properties to log4j2.xml and it should be fine.
I'm trying to use the new log4j2 with a Socket Appender but I'm a bit unlucky.
Here is my XML configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<Socket name="socket" host="localhost" port="9600">
<SerializedLayout />
</Socket>
</Appenders>
<Loggers>
<Logger name="com.mycorp" level="info" />
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="socket"/>
</Root>
</Loggers>
</Configuration>
Here is my Java code:
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.*;
import java.sql.SQLException;
import org.apache.logging.log4j.core.net.*;
public class SyslogLogger
{
private static final Logger LOG = LogManager.getLogger(SyslogLogger.class);
public static void main (String[] args)throws IOException,SQLException
{
LOG.info("commit(). Query {}", "commit(). Query {}");
}
}
When executing the code I'm getting:
2016-06-29 17:13:42,426 main ERROR Unable to write to stream TCP:127.0.0.1:9600 for appender socket: org.apache.logging.log4j.core.appender.AppenderLoggingException: Error writing to TCP:127.0.0.1:9600 socket not available
2016-06-29 17:13:42,426 main ERROR An exception occurred processing Appender socket org.apache.logging.log4j.core.appender.AppenderLoggingException: Error writing to TCP:127.0.0.1:9600 socket not available
Should I create a TCP socket explicitly? or Log4j2 does it for me?
I saw a few posts about Logstash, is that required here?
Please note that I just want to sent the messages, without actually catching them at this time.
In addition, I'm experiencing similiar issues with Syslog Adapter as well.
You need a server side to this client which logs the events to socket appender.
Your server side would look something like :
public static void main(String args[])
{
TcpSocketServer server = null;
try {
server = new TcpSocketServer(9600,new ObjectInputStreamLogEventBridge());
}
catch (IOException e)
{
e.printStackTrace();
}
server.run();
}
Here, a Tcp Socket is open on 9600 and keeps listening for log events as long as this server runs.
You would also need a log4j2 configuration corresponding to this server.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyAppServer" packages="">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console
</Appenders>
<Loggers>
<Logger name="com.mycorp" level="info" />
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Now, all the log events written by any logger which is a child to com.mycorp would be appended to console where your server runs.
Hope it helps.
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.
I cannot get Log4j 2 to log to the console. Nothing is showing up when running with gradle.
log4j2.xml in the projects root directory:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ALL">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Usage in my classes:
public class ABCHandler {
private final Logger logger = LogManager.getLogger();
public ABC(String serialPortName) {
logger.info("Opening serial port {}", serialPortName);
}
}
Loading your file and configurations on my machine works.
This was the class I used:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Test
{
private final Logger logger = LogManager.getLogger(Test.class);
public Test(String serialPortName) {
System.out.println(logger.isInfoEnabled());
logger.entry();
logger.info("info! {}", serialPortName);
logger.error("error! {}", serialPortName);
logger.debug("debug! {}", serialPortName);
}
public static void main(String args[])
{
Test h1 = new Test("1001");
}
}
This is the log4j2.xml:
<ThresholdFilter level="all"/>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p method: [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
and finally, this is the output:
true
2014-05-29 12:19:15,266 TRACE method: [main] Test (Test.java:10) - entry
2014-05-29 12:19:15,268 INFO method: [main] Test (Test.java:11) - info! 1001
2014-05-29 12:19:15,269 ERROR method: [main] Test (Test.java:12) - error! 1001
2014-05-29 12:19:15,269 DEBUG method: [main] Test (Test.java:13) - debug! 1001
One common error when using Log4j2 is placing the log4j2.xml in a file that is not in the classpath.
To diagnose if that is the problem, change the line
logger.info("Opening serial port {}", serialPortName);
to
logger.error("Opening serial port {}", serialPortName);
If you see any output it is because log4j can't load your file. This is because the default log level when the file is not found is ERROR, not DEBUG.
The location of the log4j2.xml on my project (Maven) is in src/main/resources, which I know it is in my classpath.
My problems were:
I was using a log4j.properties file. Once renamed to log4j2.properties the main and test classpaths picked it up
I had to add logging to standard output to build.gradle
test {
testLogging.showStandardStreams = true
}
note: when I added sourcesets according to here it still didn't find the log4j.properties file only renaming it worked!