HI Can you tell me please where do I put the logger code in the constructor file?
Logger logger = Logger.getLogger("MyLog");
// This block configures the logger with handler and formatter
FileHandler fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
Project is failing in the read here:
_internal_parameter_table.clear();
_internal_parameter_table.put("OPOPTT", 2);
_internal_parameter_table.put("OPOPID", templateName);
srbopt.read(_internal_parameter_table, 1);
defaultNameSrbnax01 = defaultNameSrbnax01.set(srbopt
.getBy("OPDF01"));
defaultNameSrbnox02 = defaultNameSrbnox02.set(srbopt
.getBy("OPDF02"));
defaultNameSrbcmx06 = defaultNameSrbcmx06.set(srbopt
.getBy("OPDF06"));
defaultNameSrbtpdx15 = defaultNameSrbtpdx15.set(srbopt
.getBy("OPDF15"));
defaultNameSrbnax01 = defaultNameSrbnax01.set(defaultNameSrbnax01
.trimBlanks(true, true, false, false, false));
defaultNameSrbnox02 = defaultNameSrbnox02.set(defaultNameSrbnox02
.trimBlanks(true, true, false, false, false));
defaultNameSrbcmx06 = defaultNameSrbcmx06.set(defaultNameSrbcmx06
.trimBlanks(true, true, false, false, false));
defaultNameSrbtpdx15 = defaultNameSrbtpdx15
.set(defaultNameSrbtpdx15.trimBlanks(true, true, false,
false, false));
Try this sample. It works for me.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Produces the output at MyLogFile.log
Jan 2, 2016 9:57:08 AM testing.MyLogger main
INFO: My first log
Jan 2, 2016 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
To remove the console handler, use
logger.setUseParentHandlers(false);
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
Related
I can't make my logger to work.
Inside my code I have these lines :
private static final Logger log = Logger.getLogger(ServerThread.class.getName());
log.setUseParentHandlers(false);
FileHandler fh = new FileHandler("ex.txt", true);
SimpleFormatter sf = new SimpleFormatter();
fh.setFormatter(sf);
log.addHandler(fh);
log.setLevel(Level.FINE);
And later when I get input from user :
log.log(Level.FINE,inputString);
But all that happens is that fileHandler creates a file ex.txt, but nothing is logged into the file. I am sure that log.log() is being executed.
Make sure that you only create one FileHandler and ensure that your adjust the level of your FileHandler too.
private static final Logger log = Logger.getLogger(ServerThread.class.getName());
private static final FileHandler fh;
static {
try {
log.setUseParentHandlers(false);
fh = new FileHandler("ex.txt", true);
fh.setFormatter(new SimpleFormatter());
fh.setLevel(Level.FINE);
log.addHandler(fh);
log.setLevel(Level.FINE);
} catch (IOException ioe) {
throw new ExceptionInInitializerError(ioe);
}
}
If you still don't see results then you should print the logger tree to ensure that the filehander and the loggers are created in the layout you are expecting.
In general, you should should setup a logging.properties file.
You can also use this simple approach.
public static Logger logger;
public static Logger startLogger() {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HH-mm-ss");
Date date = new Date();
String datefor = dateFormat.format(date);
logger = Logger.getLogger("MyLog");
PropertyConfigurator.configure(CLASSPATH + "/" + "log4j.properties");
Appender appender = null;
try {
appender = new FileAppender(new SimpleLayout(), CLASSPATH + "/log/MyLogFile" + datefor + ".log");
logger.addAppender(appender);
appender.setLayout(new SimpleLayout());
} catch (SecurityException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
}
Hi this is my CustomLogger class using java.util.Logger
public class CustomLogger {
private String pathToLogFiles = "/tmp/sos/logs/";
private Logger logger;
public CustomLogger(String prefix) {
logger = Logger.getLogger(prefix);
if( Utils.detectEnvironment() == Environment.LIVE ) {
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String filename = "log_" + date + ".txt";
FileHandler fileHandler = null;
try {
fileHandler = new FileHandler(this.pathToLogFiles + filename);
logger.addHandler(fileHandler);
fileHandler.setFormatter(new SimpleFormatter());
} catch (IOException e) {
logger.addHandler(new ConsoleHandler());
this.error(e.getMessage());
}
}
else {
logger.addHandler(new ConsoleHandler());
}
}
public void info(String message) {
logger.info(message);
}
public void error(String message) {
logger.warning(message);
}
}
When on Development Environment the logging to the console works fine, but on the live environment instead of logging to the one file as it should 12 different files are created containg a xml for every sent log message.
:/tmp/sos/logs# ls
log_2016-09-09.txt log_2016-09-09.txt.1.lck log_2016-09-09.txt.2.lck log_2016-09-09.txt.3.lck log_2016-09-09.txt.4.lck log_2016-09-09.txt.5.lck log_2016-09-09.txt.6.lck
log_2016-09-09.txt.1 log_2016-09-09.txt.2 log_2016-09-09.txt.3 log_2016-09-09.txt.4 log_2016-09-09.txt.5 log_2016-09-09.txt.6 log_2016-09-09.txt.lck
Can somebody tell me what is wrong there?
Thanks
Every time a CustomLogger constructor is executed you are creating and opening a new FileHandler. You need to ensure that you are only creating and adding the FileHandler once per JVM process.
Otherwise, you need to determine a proper time to close the previous FileHandler before opening a new FileHandler.
I'm trying to parse the start args in my application, but apache cli do not recognize them:
public static void main(String[] args) {
logger.debug(Arrays.toString(args)); // prints
CommandLine cmdLine = null;
HelpFormatter formatter = new HelpFormatter();
CommandLineParser parser = new BasicParser();
Options options = new Options();
options.addOption("k", true, "bla");
try {
cmdLine = parser.parse(options, args);
logger.debug("main - {}", cmdLine.hasOption("k")); // prints false
} catch (ParseException e) {
e.printStackTrace();
}
}
In Eclispe (Runconfiguration -> Arguments) I'm starting the application with k=hello
My output:
2016-07-08 15:39:34,840 DEBUG [main] (Main.java:27) - [k=hello]
2016-07-08 15:39:34,862 DEBUG [main] (Main.java:53) - main - false
The argument should be "-k hello"
i am trying to store logs into file using log4j
i tried to create one separate class
public class MyLogger {
FileHandler fh;
Logger log;
public MyLogger(String className) {
log = Logger.getLogger(className);
try {
String location = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " ").replaceFirst("/", "") + "logs.log";
fh = new FileHandler(location);
log.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
} catch (Exception e) {
System.out.println("error in MyLogger class, method getLogger \n stack trace below \n");
e.printStackTrace();
}
}
public void log(Level l, String Message, Object o) {
log.log(l, Message, o);
flushStream();
}
public void log(Level l, String Message) {
log.log(l, Message);
flushStream();
}
private void flushStream() {
fh.flush();
fh.close();
}
}
i am calling this class each and every time , when i need to log some messages to the file.
it runs fine but it overwrites the old log data each and every time it is called.
how can i append new logs using this code? or is there any other way of logging ?
There is another constructor for FileHandler which you can use to explicitly tell FileHandler that you want to append log. The code is like this:
fh = new FileHandler(location, true);
Setting the second arguments of this constructor to be true to append log.
The code is as follows:
public class Client {
static Logger l = Logger.getLogger(Client.class.getName());
public static void main(String[] args) {
Layout l1 = new SimpleLayout();
Appender a;
try
{
a = new FileAppender(l1,"my.txt", false);
l.addAppender(a);
}
catch(Exception e) {}
l.fatal("This is the error message..");
System.out.println("Your logic executed successfully....");
}
}
/*My Properties file*/
log4j.rootLogger = WARN,abc
log4j.appender.abc = org.apache.log4j.FileAppender
log4j.appender.abc.file = my111.txt
log4j.appender.abc.layout = org.apache.log4j.SimpleLayout
By using false in FileAppender(l1,"my.txt", false);
I got but if i use log4j.properties file how can I achieve this
Properties file
This is what you need:
log4j.appender.<your appender>.Append=false