How To Add Logging To A Clojure Project
This HowTo will help you get started with a working “loggable” Clojure project. Though the instructions assume that you're using Leiningen for build automation, it can be applied to any Maven based build too.
Setting Up A New Project
This creates a new empty project:
project.clj to add required dependencies:
lein deps inside logger1 directory to fetch the dependencies.
I'm not getting into the details of this rather lengthy and boring topic. Instead I'll provide you with a working configuration that I use -check out Log4j manual if you feel curious though.
Create a file named log4j.properties in src/ with the following contents:
Here's a brief description: the logger is told that the log level is DEBUG (line 1) , it should send the output to both stdout (line 1) and a rolling file called logger1.log (lines 3 & 4), it should use a new file when the current reaches 100KB (line 6), it should keep 20 log files (line 7) and it should use a certain pattern when writing log entries (lines 9 & 10). Check out Log4j pattern API for a complete description of directives used on line 10.
Using The Logger
The rest is straight forward. All you need to do is to
use the clojure.tools.logging library.
Run the application using
lein run and check out logger1.log inside ./log directory. It should contain something like [2012-09-21 10:02:31,814][INFO][logger1.core] Right there!
That's it! Your tiny application now has a working logger. Most of the times you will use
warn functions but don't forget to take a look at clojure.tools.logging API to see what's possible besides that.