Java tinylog with Multiple Writers

Tags: tinylog

In this Java tinylog tutorial we learn how to use the tinylog library to write log entries to multiple writer such as file and console.

Table of contents

  1. Add tinylog dependencies to Java project
  2. How to log entries using tinylog
  3. How to configure tinylog to logging to multiple writers

Add tinylog dependencies to Java project

To use the tinylog library in the Gradle build project, add the following tinylog dependencies into the build.gradle file.

implementation group: 'org.tinylog', name: 'tinylog-api', version: '2.4.1'
implementation group: 'org.tinylog', name: 'tinylog-impl', version: '2.4.1'

To use the tinylog library in the Maven build project, add the following tinylog dependencies into the pom.xml file.

<dependency>
    <groupId>org.tinylog</groupId>
    <artifactId>tinylog-api</artifactId>
    <version>2.4.1</version>
</dependency>
<dependency>
    <groupId>org.tinylog</groupId>
    <artifactId>tinylog-impl</artifactId>
    <version>2.4.1</version>
</dependency>

To have more information about the tinylog library you can visit the project home page at tinylog.org

How to log entries using tinylog

Firstly we write an example Java program to write some log entries using tinylog API as below.

TinyLogExample.java

import org.tinylog.Logger;

public class TinyLogExample {
    public static void main(String... args) {
        Logger.trace("Trace message");
        Logger.debug("Debug message");
        Logger.info("Information message");
        Logger.warn("Warning message");
        Logger.error("Error message");
    }
}

How to configure tinylog to logging to multiple writers

In tinylog we can configure multiple writer in tinylog.properties file with provide unique name of each writer and ensure the name must start with “writer”.

For example, the following configuration we allow the log entries to be written to both console and file writer.

src/main/resources/tinylog.properties

writerConsole        = console
writerConsole.format = {date: HH:mm:ss.SSS} {message}

writerFile           = file
writerFile.format    = {date: yyyy-MM-dd HH:mm:ss.SSS}{class}.{method}() {message}
writerFile.file      = application.log

Execute the application we have the console output as below.

01:22:30.948 Trace message
01:22:30.949 Debug message
01:22:30.949 Information message
01:22:30.950 Warning message
01:22:30.950 Error message

And log file application.log as below.

application.log

2022-04-07 01:22:30.948TinyLogExample.main() Trace message
2022-04-07 01:22:30.949TinyLogExample.main() Debug message
2022-04-07 01:22:30.949TinyLogExample.main() Information message
2022-04-07 01:22:30.950TinyLogExample.main() Warning message
2022-04-07 01:22:30.950TinyLogExample.main() Error message

Happy Coding 😊

Java tinylog Tutorial

Java tinylog Rolling File Writer

Java tinylog Tags to Different Log Files

Spring Boot logging with tinylog