How to Configure your Java Application with Log4J at Platform.sh

Goal

In this tutorial, we’ll cover the how and why to use log in your application using Log4J Platform.sh.

Preparation

This tutorial assumes you have

  • A working Java 8 application already deployed on Platform.sh.
  • A text editor of your choice.

Problems

Logging is the process of writing log messages during the execution of a program to a central place. This logging allows you to report and persist error and warning messages as well as info messages (e.g., runtime statistics) so that the messages can later be retrieved and analyzed.

Steps

1. Platform.sh log file

In Platform.sh we have two options to log your Java application.
The first one is to use the stdout where Platform.sh will handle the folder it includes to avoid the oversized in the disk issue.

This log will be at the /var/log/app.log:

https://docs.platform.sh/development/logs.html

In your log4j.properties you can set it, e.g.:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

All log files are trimmed to 100 MB automatically. But if you need to have complete logs, you can set up cron which will upload them to third-party storage. Contextual Code made a simple and well-described example how to achieve it.

2. The custom log folder

The second option is to create a new mount directory and then use it to handle your logs. The advantage is that we can create multiple records as you wish; however, you will then be responsible for purging old log files to avoid filling up the disk.

In your log4j.properties you can set, e.g.:

log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.MaxFileSize=1MB
log4j.appender.R.MaxBackupIndex=20
log4j.appender.R.File=/app/log/app.log
log4j.appender.R.Append=true
log4j.appender.R.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{MM/dd/yyyy HH:mm:ss,SSS} %-5p %c - %m%n

This time we need to create a mount folder to create your log, so we need to go in the application description file to define a writable folder to the log.

mounts:
    'log/':
        source: local
        source_path: log_source

Commit the changes and push to redeploy.

References

1 Like