I have a single file which sends SMS to different mobile networks according to command line arguements passed to it. Vodafone, 3 network, T-Mobile,O2.. etc. So, when arguement is passed
$Run SMSDaemon 3Network // sends sms to 3 networks's mobile users
$Run SMSDaemon Vodafone // sends sms to Vodafone mobile users
$Run SMSDaemon TMobile // sends sms to TMobile mobile users
$Run SMSDaemon O2 // sends sms to O2 mobile users
Now, I want to create a separate log files for separate network such that I can have log info,debug message separately according to mobile networks.
Since, I have only a single file SMSDaemon I have tried the following but it's not writing anything to file. It's only writing to a file which have been defined in log4j.properties file. So, I am confused what to write in log4j.properties and what to write in this java file??
public static void main(String[] args) {
if( args.length != 1 { return;}
networkUnique = args[0];
setLogProps(networkUnique);
//other codes and in setLogProps method
private static void setLogProps(String networkUnique)
{
log = Logger.getLogger(networkUnique);
Properties logprops=new Properties();
logprops.setProperty("log4j.appender.file","org.apache.log4j.FileAppender");
logprops.setProperty("log4j.appender.file.maxFileSize","300MB");
logprops.setProperty("log4j.appender.file.maxBackupIndex","100");
logprops.setProperty("log4j.appender.file.File","/etc/sms/"+networkUnique+".log");
logprops.setProperty("log4j.appender.file.threshold","debug");
logprops.setProperty("log4j.appender.file.layout","org.apache.log4j.PatternLayout");
logprops.setProperty("log4j.appender.file.layout.ConversionPattern","%d [%t] %-5p [%-35F : %-25M : %-6L] %-C -%m%n");
logprops.setProperty("log4j.appender.stdout","org.apache.log4j.FileAppender");
PropertyConfigurator.configure(logprops);
log.info("Log message Starting for "+ networkUnique);
}
In log4j.properties file following is written. All the logs are written to network.log file which is defined in this properties.. which is not according to my requirement. I need separate log for separate network which is defined in SMSDaemon setLogProps method.
# Define the root logger with appender file
#log = /etc/sms/
log4j.rootLogger = info, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
#log4j.appender.FILE.File=${log}/network.log
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
Please suggest.
Thanks in advance.
You need to create different appenders to achieve the goal.
Try this configurations :
<appender name="3Network" class="org.apache.log4j.FileAppender">
<param name="file" value="logs/3Network.log" />
<param name="append" value="true" />
</appender>
<appender name="Vodafone" class="org.apache.log4j.FileAppender">
<param name="file" value="logs/Vodafone.log" />
<param name="append" value="true" />
</appender>
<appender name="TMobile" class="org.apache.log4j.FileAppender">
<param name="file" value="logs/TMobile.log" />
<param name="append" value="true" />
</appender>
The same you can write as :
log4j.appender.TMobile=org.apache.log4j.FileAppender
log4j.appender.TMobile.File=logs/TMobile.log..
and so on..
Hope this will help you to get your issue resolved.
Also see this - reference
I would advice to create different Logger classes based on your network e.g.
class com.netwrok.Network1Logger{
public void logMessage(String className, String message, String Level);
}
class com.netwrok.Network2Logger{
public void logMessage(String className, String message, String Level);
}
Then update log4j.properties as below:
# Root logger option
log4j.rootLogger=INFO, RootFileAppender
#Network1 Logger option
log4j.logger.com.netwrok.Network1Logger=INFO,Network1FileAppender
#Network2 Logger option
log4j.logger.com.netwrok.Network2Logger=INFO,Network2FileAppender
# RootFileAppender - used to log messages in the root.log file.
log4j.appender.RootFileAppender=org.apache.log4j.FileAppender
log4j.appender.RootFileAppender.File=root.log
log4j.appender.RootFileAppender.MaxFileSize=100MB
log4j.appender.RootFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.RootFileAppender.layout.ConversionPattern= %5p [%t] (%F:%L) - %m%n
# Network1FileAppender- used to log messages in the shunted.log file.
log4j.appender.Network1FileAppender=org.apache.log4j.FileAppender
log4j.appender.Network1FileAppender.File=shunted.log
log4j.appender.Network1FileAppender.MaxFileSize=10MB
log4j.appender.Network1FileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.Network1FileAppender.layout.ConversionPattern= %5p [%t] (%F:%L) - %m%n
# Network2FileAppender- used to log messages in the shunted.log file.
log4j.appender.Network2FileAppender=org.apache.log4j.FileAppender
log4j.appender.Network2FileAppender.File=shunted.log
log4j.appender.Network2FileAppender.MaxFileSize=10MB
log4j.appender.Network2FileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.Network2FileAppender.layout.ConversionPattern= %5p [%t] (%F:%L) - %m%n
If you don't desire, root logger, shut it off.
Related
I created a custom appender and it's not getting called when I run my test. Here's what the properties look like:
name=config
appenders=console, myCustomAppender
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
#appender.console.layout.pattern =%d{HH:mm:ss} [%t] %c{1} [%-5level] - %msg%n
appender.console.layout.pattern=%d{dd-MM-yyyy HH:mm:ss} [%-5p] (%F:%L) - %m%n
appender.myCustomAppender = com.myCompany.logging.log4j.WindowsEventLogAppender
appender.myCustomAppender.name = WindowsEventLogAppender
appender.myCustomAppender.type = WindowsEventLogAppender
rootLogger.level=info
rootLogger.appenderRefs=stdout, myCustomAppender
rootLogger.appenderRef.stdout.ref=STDOUT
My appender is called a WindowsEventLogAppender. Any idea what's wrong with my properties file? I see the console test messages but none of the messages from my appender. Right now I'm just doing a System.out.println in my custom appender to verify it's getting called.
BTW, I've found lot's of XML examples out there for log4j2 configurations with custom appenders but none for using a properties file for configuration.
Thanks,
-Mike
I might be quite late here, but I think my answer can help other people looking for answers. Please accept this as an answer if this is correct!
If you have created a custom appender having annotation like this:
#Plugin(name = "MyCustomAppender", category = "Core",
elementType = "appender", printObject = true)
public final class MyCustomAppenderImpl extends AbstractAppender {
// other code for the plugin....
}
The log4j2 manual about Configuring Appenders states that:
"An appender is configured either using the specific appender plugin's name or with an appender element and the type attribute containing the appender plugin's name"
Meaning the type for appender should be Appender Plugin's Name attribute value.
Which in above case is MyCustomAppender (appender.identifierName.type=MyCustomAppender)
So, the Properties file configuration for this to work should be:
(Note : I have added a stdout(console) appender just to show
relevance/similarity of usage with OOTB appenders, and 2 example
usages with RootLogger and a custom logger)
# this packages attribute is important, please put comma seperated package(s) to the
# plugin(s) you have created
packages = com.package.to.your.plugin
# Example: Declare and Define OOTB Console appender, which sends log events to stdout
appender.console.name = stdout
appender.console.type = Console
# Declare and define the custom appender like this
# Note that the "abc" in "appender.abc.type" can be anything
# and the value for "appender.abc.type" should be the same as
# "Name" attribute value given in custom appender plugin which is "MyCustomAppender"
appender.abc.name=arbitrary_name
appender.abc.type=MyCustomAppender
rootLogger.appenderRef.stdout.ref = stdout
rootLogger.appenderRef.abc.ref = arbitrary_name
logger.loggeridentifier.name = com.test.SomeClass
logger.loggeridentifier.appenderRef.stdout.ref = stdout
logger.loggeridentifier.appenderRef.abc.ref = arbitrary_name
# Also note that the value of appenderRef should be the same name given to your
# appender in properties file, which in this case is "arbitrary_name" (as given above)
Try adding the packages property.
Like: packages = com.myCompany
You haven't included the package info
try the below configuration.
name=config
appenders=console, myCustomAppender
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
#appender.console.layout.pattern =%d{HH:mm:ss} [%t] %c{1} [%-5level] - %msg%n
appender.console.layout.pattern=%d{dd-MM-yyyy HH:mm:ss} [%-5p] (%F:%L) - %m%n
appender.myCustomAppender = com.myCompany.logging.log4j.WindowsEventLogAppender
appender.myCustomAppender.name = WindowsEventLogAppender
appender.myCustomAppender.type = WindowsEventLogAppender
rootLogger.level=info
rootLogger.appenderRefs=stdout, myCustomAppender
rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.com.mycompany.example=INFO,STDOUT
I have been trying to log messages from a specific class. I only want the specific messages from that class to log to a separate file and nothing else. I cant seem to get it right and I have tried multiple configurations including XML format. Id be helpful for feedback on my configuration. (see Below )
log4j2.appender.solrindexlog.type=RollingFile
log4j2.appender.solrindexlog.name=SolrIndexLog
log4j2.appender.solrindexlog.fileName=${NAME_LOG_DIR}/tomcat/solrindex.log
log4j2.appender.solrindexlog.filePattern=${NAME_LOG_DIR}/tomcat/solrindexlog-%d{yyyyMMdd}.log
log4j2.appender.solrindexlog.layout.type=PatternLayout
log4j2.appender.solrindexlog.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
log4j2.appender.solrindexlog.policies.type=Policies
log4j2.appender.solrindexlog.policies.time.type=TimeBasedTriggeringPolicy
log4j2.appender.solrindexlog.policies.time.interval=2
log4j2.appender.solrindexlog.policies.time.modulate=true
log4j2.appender.solrindexlog.policies.size.type=SizeBasedTriggeringPolicy
log4j2.appender.solrindexlog.policies.size.size=100MB
log4j2.appender.solrindexlog.strategy.type=DefaultRolloverStrategy
log4j2.appender.solrindexlog.strategy.max=5
log4j2.logger.solrindexlog.name=se.package.name
log4j2.logger.solrindexlog.level=debug
log4j2.logger.solrindexlog.appenderRefs=stdout
log4j2.logger.solrindexlog.appenderRef.stdout.ref=STDOUT
log4j2.rootLogger.level=info
log4j2.rootLogger.appenderRef.stdout.ref=STDOUT
log4j2.rootLogger.appenderRef.solrindexlog.ref=SolrIndexLog
log4j2.rootLogger.appenderRefs=stdout,solrindexlog
Try below configuration file -
appender.solrindexlog.type=RollingFile
appender.solrindexlog.name=SolrIndexLog
appender.solrindexlog.fileName=${NAME_LOG_DIR}/tomcat/solrindex.log
appender.solrindexlog.filePattern=${NAME_LOG_DIR}/tomcat/solrindexlog-%d{yyyyMMdd}.log
appender.solrindexlog.layout.type=PatternLayout
appender.solrindexlog.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.solrindexlog.policies.type=Policies
appender.solrindexlog.policies.time.type=TimeBasedTriggeringPolicy
appender.solrindexlog.policies.time.interval=2
appender.solrindexlog.policies.time.modulate=true
appender.solrindexlog.policies.size.type=SizeBasedTriggeringPolicy
appender.solrindexlog.policies.size.size=100MB
appender.solrindexlog.strategy.type=DefaultRolloverStrategy
appender.solrindexlog.strategy.max=5
logger.se.package.name.name=se.package.name
logger.se.package.name.level=debug
logger.se.package.name.additivity = false
logger.se.package.name.appenderRef.solrindexlog.ref= SolrIndexLog
logger.se.package.name.appenderRef.stdout.ref= STDOUT
rootLogger.level=info
rootLogger.additivity = false
rootLogger.appenderRef.solrindexlog.ref= SolrIndexLog
rootLogger.appenderRef.stdout.ref= STDOUT
Please change other parts of the configuration file that are not written in above configuration file like ConsoleAppender etc.
Also, as per this configuration file, all logs message will go in file as well as in console.
I am new to the Log4j framework and after reading some stuff i got some fare idea about logging mechanism, but still
i have some doubt about the following properties.
log4j.category.com.cloud.sample=INFO, file, C
log4j.additivity.com.cloud.sample=true
log4j.appender.C=org.apache.log4j.ConsoleAppender
log4j.appender.C.Target=System.out
log4j.appender.C.ImmediateFlush=true
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%-5p %d [%t] %m%n
#log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
### direct messages to file ###
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/var/basic/logs/sample.log
log4j.appender.file.Append=true
log4j.appender.file.MaxFileSize=10MB
# mylog.log.10 \u307e\u3067\u4fdd\u6301
log4j.appender.file.MaxBackupIndex=50
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %5p [%t] %c{1} - %m%n
log4j.rootLogger=INFO, C, file
In the first line of the above code contains two appenders(file, C) after that we will be having appender for both file and C. So as per my understanding logs will of category will be stored to Console and sample.log. Please let me know if i am wrong.
log4j.rootLogger=INFO, A1 and respective properties are not used right?
log4j.rootLogger=INFO, C, file: This line is about root logger, I think in my case it is not useful, because it is defined at the last line and there is no properties defined over here.
Please could any body confirm my understanding and suggest me if any changes required in the above configuration
The root logger resides at the top of the logger hierarchy. It is exceptional in three ways:
it always exists,
its level cannot be set to null
it cannot be retrieved by name.
The rootLogger is the father of all appenders. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy (including rootLogger).
I am uisng log4j in one of my applications, the code is as follows;
log=/var/lib/openshift/5372745b4382ec49cb0000d5/app-root/runtime/dependencies/jbossas/deployments/Logs/AppName.log
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
log4j.rootLogger=DEBUG, FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.append=true log4j.appender.FILE.file=${log}
log4j.appender.FILE.threshold=DEBUG
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d %-5p %c - %m%n
This application also will use some core application code which is shared between various apps - How do i therefore log from this core code base as it will be shared amongst many applications - this means i can't provide a concrete log= value
Would something like this suffice?
log=/var/lib/openshift/5372745b4382ec49cb0000d5/app-root/runtime/dependencies/jbossas/deployments/Logs/*.log
One approach would be to
have different File appenders for each appplication
Load those appeanders in the respective Application Logger.
protected static final Logger LOGGER = Logger.getLogger(X.class);
static
{
if (null == LOGGER.getAppender("TEST_LOG_APPENDER"))
{
RollingFileAppender fa = new RollingFileAppender();
fa.setName("TEST_LOG_APPENDER");
fa.setFile("/test-output/" + "App_1.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.setMaxFileSize("10MB");
fa.activateOptions();
LOGGER.addAppender(fa);
}
}
Note that here you need not to create new appender, rather remove others and use only one.
Also this will work if you have a common app level logger.
Not sure if this is a right way of doing it. But just a thought.
Given that I'm having issues trying to apply an external log4j configuration via log4j.xml I'm now interested in adopting a convention regarding the loading of resource files to Java projects.
Despite the code works displaying the message without warnings or errors, I suspect the configuration is not being really applied as changing the ConversionPattern makes no difference to the console output.
Program.java
package the.project.path;
import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
class Program {
static final Logger logger = Logger.getLogger("SampleLogger");
static final File config = new File("the.project.path/conf/log4j.xml");
static final String message = "The quick brown fox jumps over the lazy dog.";
public static void main(String[] args) {
if (config.exists()) {
PropertyConfigurator.configure(config.getPath());
} else {
BasicConfigurator.configure();
}
try {
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
logger.fatal(message);
} catch (Exception exception) {
System.out.println(exception.toString());
}
}
}
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="SampleConsoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<!--
TTCC is a message format used by log4j.
TTCC is acronym for Time Thread Category Component.
It uses the following pattern: %r [%t] %-5p %c %x - %m%n
-->
<param name="ConversionPattern" value="[%t] [%-5p] - %m%n" />
</layout>
</appender>
<root>
<appender-ref ref="SampleConsoleAppender" />
</root>
</log4j:configuration>
Any advice will be really appreciated. Thanks much in advance.
Try using the DOMConfigurator, thus:
// Load log4j config file...
String path = "/path/to/log4j.xml");
DOMConfigurator.configure(path);
// Start Logging
LOG = Logger.getLogger(Program.class);
(code ripped from my current project, so I know it works) ;-)
As well as the above use of DOMConfigurator, you can optionally set a watch period, whereby Log4J will poll the xml file for changes, every xx millis, and then reload the changes:
// Load log4j config file...
String path = "/path/to/log4j.xml");
DOMConfigurator.configureAndWatch(path, 30000); // 30sec poll
// Start Logging
LOG = Logger.getLogger(Program.class);
HTH
You can try setting -Dlog4j.debug=true to see which options are being applied to log4j.
It doesn't answer your resource loading question, but it is helpful to know that usually.