Java Logger only to file, no screen output - java

I have quite a simple problem but can't find a solution for it.
I have a logger with a file handler added, but it still spams the hell out of my console.
How could I get the logger to solely route all output to a file, with NO console outputs?

Old question but to help other developers:
You can also just use logger.setUseParentHandlers(false) on your logger.

The simplest way to guarantee that nothing will be written to the console is to put:
java.util.logging.ConsoleHandler.level = NONE
in your logging configuration file.

Remove all handlers (using Logger.getHandlers() and calling Logger.removeHandler() for each handler) from the root logger before adding your file handler.

Use log4j with
import org.apache.log4j.Logger;
Logger logger = Logger.getLogger("com.whatever");
PropertyConfigurator.configure("file-log4j.properties");
and set your display levels in file-log4j.properties:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=index-service.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.file.Append=false

I use:
Logger logger = Logger.getLogger("MyLog");
Logger parentLog= logger.getParent();
if (parentLog!=null&&parentLog.getHandlers().length>0) parentLog.removeHandler(parentLog.getHandlers()[0]);

Related

log4j not logging into file

log4j.rootLogger=INFO
log4j.logger.com.app.yum.package.WatchDog=INFO,logfile
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.file=watchdog/watchdog.log
log4j.appender.logfile.maxFileSize=1024KB
log4j.appender.logfile.maxBackupIndex=5
log4j.appender.logfile.append=true
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d | %-5p | %m | %c | %t%n
I am using above config in log4j properties file. I could see a new file has been created but there are no logs inside it.
Instead I see the logs on console. What I am trying to do is log all the logs of particular class in a file watchdog.log.
Below is my logger initialization
private static final Logger logger = LoggerFactory.getLogger(WatchDog.class);
Am I missing anything?
You need to tell the log4j to log on file,
First add:
log4j.rootLogger=INFO, FILE
Then you need to specify the file Appender like:
#settings for FILE: output to file using standard TTCC pattern
#this option backs up the file daily with a date stamp
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
#this option backs up the file after is reaches a specified size
#log4j.appender.FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.FILE.MaxFileSize=1KB
#log4j.appender.FILE.MaxBackupIndex=3
#optionally change the filepath to the log file
log4j.appender.FILE.File=D:/Reliances/reliance90e_NOVO/logs/reliance.log
log4j.appender.FILE.layout=org.apache.log4j.TTCCLayout
log4j.appender.FILE.layout.ContextPrinting=true
log4j.appender.FILE.layout.DateFormat=ISO8601
log4j.appender.FILE.Threshold=DEBUG
and to intialzed the logger you can do:
//From org.apache.log4j.Logger
Logger logger = Logger.getLogger(obj.getClass().getName());
Note: The value are an example and the also i want to show you the different options in the File Appender, also this configurations should be added to your another configurations.

Issue with log4j log not writing to file

Does anyone see why this log is not writing to file. It is writing to standard out twice but not to the file:
Also, I tried removing the "Stdout" appender and then I don't get any logging at all.
package org.berlin.wicket;
import org.apache.log4j.Logger;
private static final Logger LOG = Logger.getLogger(QuickstartPage.class);
LOG.info("Loading constructor");
log4j.rootLogger=DEBUG,Stdout,mainAppender
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%-5p - %-26.26c{1} -
%m\n
log4j.appender.mainAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.mainAppender.file=logs/core.log
log4j.appender.mainAppender.datePattern='.'yyyy-MM-dd
log4j.appender.mainAppender.append=true
log4j.appender.mainAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.mainAppender.layout.ConversionPattern=[%d{MM/dd/yyyy
HH:mm:ss.SSS}] [%C{1}.%M():%L] [%t] [%p] - %m%n
log4j.logger.org.berlin=DEBUG,Stdout,mainAppender
You have two loggers which use the same appender (Stdout), hence why you see entries on the console twice.
As others have mentioned, the properties are case-sensitive, hence why your file appender is not configured correctly.
The File and Append properties are case senstive.
log4j.appender.mainAppender.File=someFileName.log
log4j.appender.mainAppender.Append=true
You should create an instance of FileHandler that writes log to a file called myfile.log.
FileHandler fileHandler = new FileHandler("myfile.log", true);
logger.addHandler(fileHandler);

Java Log4j overwrite output of FileAppenders

I am using Log4j for logging output of my application.
The log4j.properties files contents the following:
log4j.logger.DEFAULT_LOGGER=INFO,main_log, stdout
log4j.additivity.DEFAULT_LOGGER = false
# Direct log messages to a log file
log4j.appender.main_log=org.apache.log4j.FileAppender
log4j.appender.main_log.File=mainLog.log
log4j.appender.main_log.layout=org.apache.log4j.PatternLayout
log4j.appender.main_log.layout.ConversionPattern=%d{yyyy mm dd HH:mm:ss} %5p %c{1}:%L - %m%n
# 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 - %m%n
Currently the following happens. When I start my main method where I call
static Logger log = Logger.getLogger("DEFAULT_LOGGER");
log.fatal("Process Logger");
it prints the output to stdout and file.log, which is fine. But when I start my application a second time it adds the output to the existing file. But I want to overwrite the log file. Is this possible? (I dont want to use Java for deleting, also I dont want to delete it manually of course) Is there an option in Log4J to tell the logger is to overwrite or the add output?
You need to use RollingFileAppender for this.
Check following SO questions on similar lines:
Post One
Post Two
You can use FileAppender, add log4j.appender.fileAppender.Append=false property to it

Log4J loggers for different classes

I want to use Log4J for logging my java projects.
I created a log4j.properties file in the src directory with the following content:
# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.logger.DEFAULT_LOGGER=INFO,file2
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=file.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# 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{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.file2=org.apache.log4j.FileAppender
log4j.appender.file2.File=file2.log
log4j.appender.file2.layout=org.apache.log4j.PatternLayout
log4j.appender.file2.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
For example I want to use the "DEFAULT_LOGGER" only in my main method. So I wrote:
static Logger log = Logger.getLogger("DEFAULT_LOGGER");
log.fatal("Process Logger");
But when I execute the main method I prints the message "Process Logger" to all Appenders (stdout, file and file2) But I only want to print it out to file2. How can I do that or better ro say what do I do wrong?
The second point is, when I execute the main method the second time, it does not overwrite file and file2, it justs adds a line inside the textfile. How can I avoid that?
Log4j has something called additivity. by default it is set to true and it means that every log you write will not only be logged by the specific logger but also by its ancestors (the root logger in this case).
To set it to false try this:
log4j.additivity.DEFAULT_LOGGER = false
Learn more about it here.
try:
log4j.additivity.DEFAULT_LOGGER = false

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