Santhosh Bhupathi
Santhosh Bhupathi

Reputation: 11

Need to print date in stdout logfile of tomcat

We have a web application, now we want to print date at stdout log file, actually we are printing the output using System.out.println() in so many java files. So, we want date & time in stdout/stderr logfiles at where we are getting the output(with out changing java files). please help me.

Upvotes: 1

Views: 471

Answers (1)

desilijic
desilijic

Reputation: 104

In the begin of programm you can override println() for your System.out and add new Date()

System.setOut(new PrintStream(System.out) {
    @Override
    public void println(String s) {
       Date date = new Date();
       super.println(String.format("[%s] %s"), date, s);
    }
})

The same you can do with System.setErr()

If you allow to use Java Instrumentation then you can use Agent

package com.test.agent;

import java.io.PrintStream;
import java.lang.instrument.Instrumentation;
import java.util.Date;

public class AgentOutRewrite {

    public static void premain(String agentArgument, Instrumentation instrumentation) {
        System.out.println("Agent VM replacement");

        System.setOut(new PrintStream(System.out) {
            @Override
            public void println(String str) {
                super.println(new Date() + ": " + str);
            }
        });
    }
}

With MANIFEST.MF

Manifest-Version: 1.0
Premain-Class: com.test.agent.AgentOutRewrite

If you create jar with this class for example Agent.jar you can inject you agent into your program like that

java -javaagent:Agent.jar YourProgram.jar

For adding Agent to Tomcat you should change CATALINA_OPTS

CATALINA_OPTS="$CATALINA_OPTS -javaagent:/path/to/YourAgentJar.jar"

just as in this post Adding -javaagent to Tomcat 6 server, where do I put it and in what format?

Upvotes: 1

Related Questions