I am trying to create multiple logs in Log4j, but I am facing a weird problem. Here's the log4j.properties and the code implementing it.
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILEALL
# Define the file appender
log4j.appender.FILEALL=org.apache.log4j.FileAppender
log4j.appender.FILEALL.File=${logfile.name}
# Define the layout for file appender
log4j.appender.FILEALL.layout=org.apache.log4j.HTMLLayout
#log4j.appender.FILEMAIN=org.apache.log4j.FileAppender
#log4j.appender.FILEMAIN.File=${logfilemain.name}
#log4j.appender.FILEMAIN.layout=org.apache.log4j.HTMLLayout
I have added the statement when running both and removed the original one
log4j.rootLogger = DEBUG, FILEALL , FILEMAIN
And this is the java code:
System.setProperty("logfile.name", savePath1);
// System.setProperty("logfilemain.name", savePath1);
logger = Logger.getLogger(HarishLog.class.getName());
PropertyConfigurator.configure("log4j.properties");
The code works perfectly fine till I make one log, but as soon as I enable the setting for 2nd log in either the properties or the javafile, nothing happens.
Besides I am unable to put a different name at
log4j.appender.FILEALL.File=${logfile.name}
it only works for logfile.name and logfilea.name, It doesn't work for any other name if I change it both in the javacode and the properties folder. Why is this???
Thank you
This works for me:
log4j.rootLogger = DEBUG, FILEALL, FILEMAIN
log4j.appender.FILEALL=org.apache.log4j.FileAppender
log4j.appender.FILEALL.File=${logfile.name}
log4j.appender.FILEALL.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILEMAIN=org.apache.log4j.FileAppender
log4j.appender.FILEMAIN.File=${logfilemain.name}
log4j.appender.FILEMAIN.layout=org.apache.log4j.HTMLLayout
import org.apache.log4j.Logger;
public class LogTest {
public static void main(final String... args) {
System.setProperty("logfile.name", "logall.txt");
System.setProperty("logfilemain.name", "logmain.txt");
Logger logger = Logger.getLogger(LogTest.class.getName());
logger.info("hello");
}
}
If you're still having problems, try adding:
log4j.debug = true
to the beginning of your log4j.properties, and check the output messages.
Related
It is possible so simple, but I've wasted already a lot of time to find any solution.
I have
package net.rubyeye.xmemcached;
...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
public class XMemcachedClient implements XMemcachedClientMBean, MemcachedClient {
private static final Logger log = LoggerFactory
.getLogger(XMemcachedClient.class);
....
With Log4j I get all logs from apache-servicemix.
I've tried something like
log4j.logger.net.rubyeye.xmemcached.XMemcachedClient=All, xmemcachedLog
log4j.appender.xmemcachedLog=org.apache.log4j.RollingFileAppender
log4j.appender.xmemcachedLog.File=${karaf.data}/log/spring/xmemcachedLog.log
log4j.appender.xmemcachedLog.ImmediateFlush=true
log4j.appender.xmemcachedLog.maxFileSize = 10MB
log4j.appender.xmemcachedLog.maxBackupIndex = 10
log4j.appender.xmemcachedLog.layout=org.apache.log4j.PatternLayout
log4j.appender.xmemcachedLog.layout.ConversionPattern=%d{dd-MM-yyyy_HH:mm:ss} %-5p [%t] - %m%n
But I don't get anything. I want to get information about exception which I get on the 1335th line
key = this.preProcessKey(key);
Actually, it doesn't matter that I want to log exactly that class. In my application I also have other classes which have LoggerFactory.getLogger(...);
And the main question is
How to get logs from Logger log = LoggerFactory
.getLogger(SomeClass.class);
Now, my rootLogger looks like
# Root logger
log4j.rootLogger=info, out, sift, osgi:VmLogAppender
log4j.throwableRenderer=org.apache.log4j.OsgiThrowableRenderer
You should have a logback.xml somewhere which decide to show your log or not if you're on a java EE application.
Try to add this line of code into it:
<logger name="net.rubyeye.xmemcached" level="DEBUG"/>
It will activate DEBUG logs for all the classes in this package.
If it still doesn't work maybe you don't have the file in your classpath and you might have to add it in the jvm parameter.
There is no problem in my logger. I've just hadn't any log.error() or log.smth() so I haven't got any lines in my files.
So it would work, for example, in that method inside XMemcachedClient
public void setTimeoutExceptionThreshold(int timeoutExceptionThreshold) {
if (timeoutExceptionThreshold <= 0) {
throw new IllegalArgumentException(
"Illegal timeoutExceptionThreshold value "
+ timeoutExceptionThreshold);
}
if (timeoutExceptionThreshold < 100) {
log.warn("Too small timeoutExceptionThreshold value may cause connections disconnect/reconnect frequently.");
}
this.timeoutExceptionThreshold = timeoutExceptionThreshold;
}
It shows me "Too small timeoutExceptionThreshold value may cause connections disconnect/reconnect frequently." in my ${karaf.data}/log/spring/xmemcachedLog.log when timeoutExceptionThreshold < 100
I want to use log4j for generating the logs.
For this I am using the following code :
package com.idm.Test;
import org.apache.log4j.Logger;
public class log4jExample {
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args) {
log.info("Hello this is a debug message 1");
log.info("Hello this is a debug message 2");
log.info("Hello this is a debug message 3");
}
}
My log4j properties file is given below :
# Define the root logger with appender file
log=G:\\logs
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}\\log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
I want to generate log file inside
G:\logs\log.out
But the problem is that when I run this. There is no log file is created on this path.
When I already created one file into that location with log.out name and run again it is not showing me the logs inside this file.
I put my log4j.properties file inside com.idm.Test package.
You are using the the Java Util Logger in your code
import java.util.logging.Logger;
this is not the log4j logger. Fix your import and ensure that your configuration file will be found (either put in on the classpath or specifiy the location with the log4j.configuration system property - see here)
Note: OP edited question and uses the right import now...
By the way do not use log4j (1) anymore. It has reached its EOL and is not Java 9 ready.
Go with log4j2 (or other current logging frameworks) instead.
I did same like your code and properity, and log file was created.
In my case, log4j.properties is located in the root of class path.
i.e.)
classes/log4j.properties
classes/com/idm/Test/log4jExample
please, check the location of log4j.properties.
You should put log4j.properties in resource folder (source/main/resource), i think it will work correctly.
In case your project is java project (not maven project) i think you should change your code:
package com.idm.Test;
import org.apache.log4j.Logger;
public class log4jExample {
static Logger log = Logger.getLogger(log4jExample.class.getName());
public static void main(String[] args) {
**PropertyConfigurator.configure("yourPath/log4j.properties");**
log.info("Hello this is a debug message 1");
log.info("Hello this is a debug message 2");
log.info("Hello this is a debug message 3");
}
}
please check the attached image of project structure, let me know if i positioned log4j2.properties right.
also have a look at versions of jars I am using.
I wrote a simple program to print logs on console. in order to achieve this I wrote log4j2.properties file as follows.
Root logger option
log4j.rootLogger=INFO, file
log4j.appender.file= org.apache.logging.log4j.core.appender.ConsoleAppender
log4j.appender.file.Target=System.out
log4j.appender.file.Layout=org.apache.logging.log4j.core.layout.PatternLayout
log4j.appender.file.Layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Main program is as follows.(also shown in image)
package goldensource.track.logs;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.PropertiesUtil;
public class TestLogger {
private Logger logger;
private PropertiesUtil pu;
TestLogger()
{
System.setProperty("log4j.configurationFile","log4j2.properties");
logger = LogManager.getLogger(TestLogger.class);
logger.info("Yes I am there!");
logger.debug("I am debugging!");
logger.warn("giving you a warner!");
}
public static void main(String[] args) {
TestLogger z = new TestLogger();
}}
I have created a reference of PropertiesUtil but anyways I am not using it.
when I am executing this program nothing is shown on console. as I could make out, I am not able to load properties file properly.
suggest me any modifications or alternatives with examples.
Thanks in advance!
Without any feedback on the error you are getting, I can guess that one of the problems is with the file name. You should specify the absolute path to your log4j2.properties file when you are setting the system property:
System.setProperty("log4j.configurationFile","/absolute/path/to/log4j2.properties");
In this way the logger system will know exactly where to find your file.
I want specific messages generated from within the same class to be logged separately. So, how can I create 2 different types of loggers within the same class. Currently, the Properties file looks like
log4j.rootCategory=DEBUG, O
# Stdout
log4j.appender.O=org.apache.log4j.ConsoleAppender
log4j.appender.O.layout=org.apache.log4j.PatternLayout
log4j.appender.O.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
# File
log4j.appender.MESSAGE=org.apache.log4j.RollingFileAppender
log4j.appender.MESSAGE.File=target/logs/messages.log
# Control the maximum log file size
log4j.appender.MESSAGE.MaxFileSize=1000KB
# Archive log files (one backup file here)
log4j.appender.MESSAGE.MaxBackupIndex=100
log4j.appender.MESSAGE.layout=org.apache.log4j.PatternLayout
log4j.appender.MESSAGE.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M (% F:% L) - %m%n
log4j.appender.MESSAGE.
log4j.category.failedMessagesLog=INFO, MESSAGE
I'm using the logging in my code as: –
/** Logger. */
Logger logger = Logger.getLogger(MyClass.class);
Logger msgLogger = Logger.getLogger("MESSAGE");
Upon testing, I get an empty log file (messages.log) created.
Any suggestions??
Create two loggers with different names. You can configure them on a per name basis.
A simple way to do this is to add a suffix to you class name. e.g.
Log log1 = LogFactory.getLog(getClass().getName()+".log1");
Log log2 = LogFactory.getLog(getClass().getName()+".log2");
in your properties file.
log4j.category.mypackage.myclass.log1=INFO, MESSAGE1
log4j.category.mypackage.myclass.log2=INFO, MESSAGE2
log4j.rootCategory=DEBUG, O
log4j.appender.O=org.apache.log4j.ConsoleAppender
log4j.appender.O.layout=org.apache.log4j.PatternLayout
log4j.appender.O.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
log4j.appender.MESSAGE=org.apache.log4j.RollingFileAppender
log4j.appender.MESSAGE.File=target/logs/messages.log
log4j.appender.MESSAGE.MaxFileSize=1000KB
log4j.appender.MESSAGE.MaxBackupIndex=100
log4j.appender.MESSAGE.layout=org.apache.log4j.PatternLayout
log4j.appender.MESSAGE.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M
log4j.appender.**MESSAGE2**=org.apache.log4j.RollingFileAppender
log4j.appender.**MESSAGE2**.File=target/logs/**messages2**.log
log4j.appender.**MESSAGE2**.MaxFileSize=1000KB
log4j.appender.**MESSAGE2**.MaxBackupIndex=100
log4j.appender.**MESSAGE2**.layout=org.apache.log4j.PatternLayout
log4j.appender.**MESSAGE2**.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M
log4j.category.failedMessagesLog=INFO, MESSAGE , **MESSAGE2**
"failedMessagesLog" is the java file to which appender (INFO,MESSAGE, MESSAGE1) is applied.
I have just reused existing RollingFileAppender. you can use any other appender ( like fileAppender).
You should use the right Class name Logger logger = Logger.getLogger(MyClass.class)
should be changed to private static final Logger log = Logger.getLogger( **failedMessagesLog.class** );
Make sure you are using log4j's logging ie
import **org.apache.log4j.Logger**;
I've an issue with a project I try to deliver using the one-jar packager to simplify the deployment process.
Without the packaging, everything works fine and the logging configuration is perfectly loaded, but within the packaging, only part of the configuration is appied.
So, here is the logging.properties I use:
handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler
.level= INFO
java.util.logging.FileHandler.pattern = C:\\MyPath\\logging.csv
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = my.package.logging.Formatter
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = my.package.logging.Formatter
And In my main class, here is how I load it:
public class MainClass {
public static void main(final String[] args) {
try {
LogManager.getLogManager().readConfiguration(
new MainClass().getClass().getResourceAsStream("logging.properties"));
// main process goes here.
} catch(Exception e) {
// Exception handling
}
}
}
The log level as well as the FileHandler pattern are well understood because the logging ends up in the correct file, but as row XML output, which makes me think that the formatter is not loaded as it normally outputs a CSV format.
Could it be related to a classpath issue? Does anyone knows how to handle this?
It could be in your jars you have more than one logging.properties file, with similar but slightly different settings. When you combine them with one-jar the order changes and one of them gets hidden. Do a "jar -tf *.jar |grep logging.properties" and see what you see.
If that doesn't work can you try unjarring the onejar result to a directory structure, and then running with the directory on the classpath instead of the jar? That will let you see if it is something to do with the jar, and actually inspect the logging.properties you have in the onejar, and see if it matches what you expect.
Use LogManager.getLogManager().readConfiguration(LogManager.class.getResourceAsStream("/logging.debug.properties"));
(note the extra slash).