How to create a custom logger file with a specific timestamp


How to create a custom logger file with a specific timestamp



If you need to create a new logger from a specific Jenkins Handler with a specific timestamp you need to create a groovy script.

This groovy script should be included in your $JENKINS_HOME/init.groovy (if the file doesn’t exist, you’ll need to create it with this script) that will add a logger with the handler and new timestamp format.

You need to modify the path of the log file (PATHTOLOG) in the script with the path of your local system where you like to save it.

import java.util.logging.ConsoleHandler
import java.util.logging.FileHandler
import java.text.MessageFormat
import java.util.logging.SimpleFormatter
import java.util.logging.LogManager
import jenkins.model.Jenkins
import java.util.logging.LogRecord

// Log into the console
def WebAppMainLogger = LogManager.getLogManager().getLogger("hudson.WebAppMain")
WebAppMainLogger.addHandler (new ConsoleHandler())

// Log into a file
def RunLogger = LogManager.getLogManager().getLogger("hudson.model.Run")
def logsDir = new File(Jenkins.instance.rootDir, "logs")
FileHandler handler = new FileHandler("PATHTOLOG/hudson.model.Run-%g.log", 1024 * 1024, 10, true);
def formatter= (new SimpleFormatter() {
        private static final String format = "%1\$tY-%1\$tm-%1\$tdT%1\$tH:%1\$tM:%1\$tS %4\$s %10\$s %n%2\$s %14\$s %n";
          public synchronized String format(LogRecord lr) {

              return String.format(format,new Date(lr.getMillis()),lr.getLevel().getLocalizedName(),lr.getMessage(),lr.getLoggerName(),lr.getParameters(),lr.getResourceBundle(),lr.getResourceBundleName(),lr.getSequenceNumber(),lr.getSourceClassName(),lr.getSourceMethodName(),lr.getThreadID(),lr.getThrown(),lr.getLevel().getName(),formatMessage(lr));


If you need to modify the timestamp format you should need to modify:

private static final String format = "%1\$tY-%1\$tm-%1\$tdT%1\$tH:%1\$tM:%1\$tS %4\$s %10\$s %n%2\$s %14\$s %n";

In the references section, you have the guides of how to modify the format.


Tested products/plugins version

The latest update of this article was tested with:

  • Jenkins core 2.60.2 API
Have more questions? Submit a request


Please sign in to leave a comment.