recording logs with logback


references

com.github.jinahya:jinahya-logback

<dependency>
  <!-- scoped as usual -->
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <!-- no transitive dependency for logback -->
  <groupId>com.github.jinahya</groupId>
  <artifactId>jinahya-logback</artifactId>
  <scope>compile</scope>
</dependency>

BufferedOutputStreamAppender

LogRecorder and LogRecorderReflector

JAX-RS

Lets say you have a hidden @POST method for testing.

@Path("/tests")
public class TestsResource {

    // tests HisService by calling doSome().
    // you can see the log file.
    @POST
    @Path("/his-service")
    public Response hisService() {
        logger.debug("testing his service...");
        hisService.work();
        logger.debug("done.");
        return Response.noConent().build();
    }
}

You have to connect to the server and tail the log file even if you execute the resource like this.

$ curl -X POST http://www.doma.in/my-app/tests/his-service

Let’s make another method which returns some buffered logs.

@Path("/tests")
public class TestsResource {

    @GET
    @Path("/his-service/log")
    @Produces({MediaType.TEXT_PLAIN})
    public Response hisServiceLog() throws ReflectiveOperationException {
        // start recording.
        // logger, pattern, charset, limit
        recorder = LogRecorderReflector.start(
            getLogger(Logger.ROOT_LOGGER_NAME), "%message%n",
            StandardCharsets.UTF_8, 8192);
        try {
            hisService();
        } catch (final Exception e) {
            logger.error("error while executing fileBack()", e);
        }
        // finish recording and get the records.
        final String records = LogRecorderReflector.finish(recorder);
        return Response.ok(records).build();        
    }
}

Now we can see those buffered logs in a local console or a browser window.

$ curl http://www.doma.in/my-app/tests/his-service/log
...
I'm doin' some baby.
...
Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s