How to handle more than two appenders logging separately - java

We are moving from Log4j1 to log4j2. I am able to create multiple files and added logging in those files like below:
name=PropertiesConfig
appenders = file1, file2
appender.file1.type = File
appender.file1.name = LOG1FILE1
appender.file1.fileName= ./logs/operation.log
appender.file1.layout.type=PatternLayout
appender.file1.layout.pattern= %-d{yyyy MMM dd HH:mm:ss:SSS} GMT %-d{Z} %-5p[%t] %m%n
appender.file2.type = File
appender.file2.name = LOGFILE
appender.file2.fileName= ./logs/Connection.log
appender.file2.layout.type=PatternLayout
appender.file2.layout.pattern= %-d{yyyy MMM dd HH:mm:ss:SSS} GMT %-d{Z} %-5p[%t] %m%n
rootLogger.level = info
rootLogger.additivity = false
rootLogger.appenderRefs = logfile
rootLogger.appenderRef.logfile.ref = LOGFILE
rootLogger.appenderRefs = LOG1FILE1
rootLogger.appenderRef.LOG1FILE1.ref = LOG1FILE1
I need to understand, how I can do logging in one particular file for a particular type of appender. I was able to do this in log4j1 earlier. Let's consider I have two appenders one is for Connection and another one is for Operation, so when instantiating the connection, write logs in Connection.log file whereas when operation is performing the logging happens in operation.log file. So same thing I wanted to handle in log4j2.

In Log4j 1.x you attached each appender to a different logger. In Log4j 2.x you just need to do the same:
logger.1.name = BusinessFunction
logger.1.level = TRACE
logger.1.appenderRef.1.ref = LOG1FILE1
logger.2.name = Connection
logger.2.level = TRACE
logger.2.appenderRef.1.ref = LOGFILE
You should also consider attaching the root logger to a file.

Related

All Messages of Referenced Jar to Log File + Setting up Encoding of Log File to UTF-8 to display Japanese Characters (Log4j2)

I have 2 questions regarding Log4j2.
How can I set that warnings and errors of referenced Jar files to output in the log file instead of the console? Currently, log statements in my application are being printed in the log file. But those messages from the referenced Jar files are being printed in the console instead.
How can I set Japanese characters to be printed in the generated logfile? Currently, I have set charset of layout but the output of Japanese characters are still in "?" or garbage characters.
This is my current property file:
status = error
name = PropertiesConfig
property.filename = ${sys:user.home}\\myApp\\logs\\application.log
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
#filter.threshold.level = info
appenders = rolling
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = ${sys:user.home}\\myApp\\logs\\log-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.zip
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.layout.charset = "UTF-8"
appender.rolling.policies.type = Policies
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=1MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
loggers = rolling
logger.rolling.name = org.mycom.myproj.tools.myapp
logger.rolling.level = all
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile
rootLogger.level = all
rootLogger.appenderRefs = rolling
rootLogger.appenderRef.rolling.ref = RollingFile
I assume you mean 'external third party libraries' by 'referenced jar files'. Libraries usually use a logger abstraction like apache.commons.logging or slfj4 for issuing its log outputs.
You need to add an additional dependency which bridges these log outputs correctly to your log4j2-Logger. e.g. "org.apache.logging.log4j:log4j-slf4j-impl:2.7".
If you do not provide such a bridge the log abstraction framework might do default initialization (which probably logs to console).

Log4j2 RollingFile: Use todays date in current logfile (refreshing fileName)

I had a webservice using log4j, and upgraded it to use log4j2 so I could take advantage of the way log4j2 can delete old log dated log files for you while log4j can't.
The logs are stored in the pattern /my_log_root/yyyyMMdd/myservice.log. The relevant log4j.properties config looked like this:
log4j.appender.RollingAppender=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.RollingAppender.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.RollingAppender.RollingPolicy.FileNamePattern=/my_log_root/%d{yyyyMMdd}/myservice.log
This worked well, except old log files were never deleted. Now in log4j2 the properties file looks like this:
property.basePath = /my_log_root/
appender.rolling.type = RollingFile
appender.rolling.fileName= ${basePath}/${date:yyyyMMdd}/myservice.log
appender.rolling.filePattern= ${basePath}/%d{yyyyMMdd}/myservice.log
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.delete.type = Delete
appender.rolling.strategy.delete.basePath = ${basePath}
appender.rolling.strategy.delete.maxDepth = 3
appender.rolling.strategy.delete.ifLastModified.type = IfLastModified
appender.rolling.strategy.delete.ifLastModified.age = 30d
With this properties file, the old log files are deleted (the empty directories remain, but that's not too bad).
The only problem is with the current days log. It appears as if log4j2 is never refreshing the fileName once it's calculated. For example, when I relaunched the service on 2019-06-21, it wrote the file correctly to /my_log_root/20190621/myservice.log. However, now a few days later, it's still writing the current log to /my_log_root/20190621/myservice.log. At the end of the day it will rotate the log to the appropriate dated directory, and then start writing the new log to the 21st.
Is it possible to make log4j2 refresh it's current logs location each day or does it not support this?

Log4J out to console and file produces warnings/errors log4j:WARN File option not set for appender

I'd like to integrate Log4J logging into my Java application, writing information out to a log file as well as displaying the info at the console. Unfortunately, I've had some trouble getting this off the ground. I'm working with Eclipse Juno on Win 7.
My log4j.properties file:
#configure logfile
log4j.appender.logfile = org.apache.log4j.RollingFileAppender
log4j.appedner.logfile.File = MyAppLog.log
log4j.appender.logfile.Append = true
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern = %-5p %d [%t][%F:%L] : %m%n
#configure 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 = %-5p %d [%t][%F:%L] : %m%n
log4j.rootLogger = debug, logfile, stdout
I belive the above follows the pattern of some other accepted answers on this topic.
I've specifed the location of this log4j.properties file wtih a VM argument:
-Dlog4j.configuration=file:///${workspace_loc}\path\to\file\log4j.properties
I instantiate the logger in my java class:
static Logger logger = Logger.getLogger(MyApp.class.getName());
log a string:
logger.info("barfoo");
This configuration results in the following warnings/errors on launch:
log4j:WARN File option not set for appender [logfile].
log4j:WARN Are you using FileAppender instead of ConsoleAppender?
log4j:ERROR No output stream or file set for the appender named [logfile]
It does not produce the log file. The console logging seems to be working just fine, however.
This will sound stupid - you have a typo. You have log4j.appedner.logfile.File instead of log4j.appender.logfile.File (note the 'n' and 'd' are switched). This is why it's complaining that you haven't set the File.

How to invoke a new notepad with Java and save it in a directory in windows?

I am currently logging test execution results in to a textfile(An existing one.) How do I create a textfile with a timestamp and save it in a windows directory? The code I am using currently is
File outputResultFile = new File(CompleteFileNameForNotepad);
PrintWriter outputFile = new PrintWriter(new FileWriter(outputResultFile));
String str = "text to write in to the file";
outputFile.println(str);
outputFile.close();
Thanks for your help.
String fileName = new SimpleDateFormat("yyyy-MM-ddTHH-mm-ss").format(new Date()) + ".txt";
File outputResultFile = new File(fileName);
...
Note: what you call a notepad is more commonly called a "file".
You should consider using a logging framework instead. Check out Log4j for example. You can then alter the logging format and which classes are logged by tweaking the logging configuration. This means you don't have to alter your code.
The log4j.properties below would log all classes under the package foo, at WARN level or higher to the Console, using the pattern "2000-09-07 14:07:41,508 [main] INFO MyApp - Entering application."
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.foo=WARN
To log to a file use a different Appender, such as org.apache.log4j.FileAppender or org.apache.log4j.RollingFileAppender. For your purpose org.apache.log4j.DailyRollingFileAppender would be suitable.

configure log4j to log to custom file at runtime

Can anyone please guide me as to how I can configure log4j to log to a specific file that I specify at run-time.The name and path of the log file are generated at run-time and the application must log to that particular file.
Generally file appender entries in the log4j.properties file points to the log file that will be used by the application.However in this case I would like to read the log file path from the command line and log to that particular file.
How can I achieve this ?
You can also do this from the log4j.properties file. Using the sample file below I have added the system property ${logfile.name}:
# logfile is set to be a RollingFileAppender
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${logfile.name}
log4j.appender.logfile.MaxFileSize=10MB
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p]%d{yyyyMMdd#HH\:mm\:ss,SSS}\:%c - %m%n
The log file name can then be set two different ways:
As a command line, system property passed to java "-Dlogfile.name={logfile}"
In the java program directly by setting a system property (BEFORE you make any calls to log4j).
System.setProperty("logfile.name","some path/logfile name string");
Adapted from the log4j documentation:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
public class SimpandFile {
static Logger logger = Logger.getLogger(SimpandFile.class);
public static void main(String args[]) {
// setting up a FileAppender dynamically...
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"your filename",false);
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}
Can be also done by this properties define in log4j.properties file
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.maxFileSize=5000KB
log4j.appender.logfile.maxBackupIndex=5
log4j.appender.logfile.File=/WebSphere/AppServer/profiles/Custom01/error.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p [%t] %C %M %c{1}:%L - %m%n
Working and same has been tested
// setting up a FileAppender dynamically...
SimpleLayout layout = new SimpleLayout();
RollingFileAppender appender = new RollingFileAppender(layout,"file-name_with_location",true);
appender.setMaxFileSize("20MB");
logger.addAppender(appender);
Just remove your log4j code and replace this code in your java class it's working good no need to add properties or xml file
SimpleDateFormat dateFormatsd = new SimpleDateFormat("dd-MM-yyyy-hh-mm");
String dateandtime=dateFormatsd.format(new Date());
SimpleLayout layout = new SimpleLayout();
RollingFileAppender appender = new RollingFileAppender(layout,".\\Logs\\log "+dateandtime+".txt",true);
appender.setMaxFileSize("20MB");
logger.addAppender(appender);
The above code will log the logs for every minute.
Thanks

Categories