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.
            Asked
            
        
        
            Active
            
        
            Viewed 442 times
        
    1
            
            
         
    
    
        Insane Skull
        
- 9,220
- 9
- 44
- 63
 
    
    
        Santhosh Bhupathi
        
- 11
- 2
- 
                    1Welcome to Stack Overflow! I edited the title of your question to include the name of the function you're calling, so more people with knowledge of the subject will see it. I also indented your code sample by 4 spaces so that it renders properly - please see the editing help for more information on formatting. Please edit in the specific error-message you're encountering in case that's necessary to identify the specific problem. Good luck! – bozzmob Jan 28 '16 at 04:56
1 Answers
1
            
            
        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?
- 
                    
- 
                    @SanthoshBhupathi I have added another approach without changing original code. – desilijic Jan 29 '16 at 16:27
 
    