Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging with multiple parameters

I am currently working on a program wherein, I must write all output to a log file.

I need to write a log method, that should give an output with a level, a message, an object value, another message, an integer value, another message and another integer value, in the same order as I have specified. I can't seem to find a log method that does this. I am using Java.util.logging. Is this possible?

like image 300
Gash87 Avatar asked Apr 08 '13 13:04

Gash87


People also ask

What is parameterized logging?

Advantage of Parameterized LoggingThis involves the conversion of the integer value 23 to string and concatenation of this value to the strings surrounding it. And if it is a logging statement, and if that particular log level of your statement is disabled then, all this calculation will be of no use.

What is marker in SLF4J?

Markers are named objects used to enrich log statements. Conforming logging system Implementations of SLF4J determine how information conveyed by markers are used, if at all. In particular, many conforming logging systems ignore marker data.

What does logger info do?

The info() method of a Logger class is used to Log an INFO message. This method is used to forward logs to all the registered output Handler objects. INFO message: Info is for the use of administrators or advanced users.

What is a logger Java?

Loggers in Java are objects which trigger log events, They are created and are called in the code of the application, where they generate Log Events before passing them to the next component which is an Appender. You can use multiple loggers in a single class to respond to various events or use Loggers in a hierarchy.


Video Answer


1 Answers

I assume you need the log format in the below format FINE,Message1,object.GetValue(),Message2,1,Message3,2

You need to create an output message format

logger.log(Level.INFO, "{0},{1},{2},{3},{4},{5}",new Object[]{Message1,object.getValue(),Message2,1,Message3,2}); 

Now you need to create a custom formatter which by extending Formatter class

public class DataFormatter extends Formatter {  @Override public synchronized String format(LogRecord record) {     String formattedMessage = formatMessage(record);     String throwable = "";     String outputFormat = "%1$s, %2$s \n %3$s"; //Also adding for logging exceptions     if (record.getThrown() != null) {         StringWriter sw = new StringWriter();         PrintWriter pw = new PrintWriter(sw);         pw.println();         record.getThrown().printStackTrace(pw);         pw.close();         throwable = sw.toString();     }     return String.format(outputFormat,record.getLevel().getName(),formattedMessage,throwable); } } 

Now set the newly created formatter

    for(int i=0;i<logger.getHandlers().length;i++)         logger.getHandlers()[i].setFormatter(new DataFormatter()); 
like image 70
Rohit Avatar answered Sep 21 '22 22:09

Rohit