Logging in Clojure with clj-logging-config

So your Clojure app wants to write logfiles. It’s easier than it used to be, thanks to Malcom Sparks and his clj-logging-config project. All the messy and utterly static log4j.properties stuff has been wrapped up in a nice dynamic Lisp layer! Here’s how.

First, set up your project.clj file to load the appropriate libraries:

(defproject my-project "1.0.0-SNAPSHOT"
  :description "My Project"
  :dependencies [
                 [org.clojure/clojure "1.3.0"]

                 [log4j/log4j "1.2.16" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]]
                 [org.slf4j/slf4j-log4j12 "1.6.4"]
                 [org.clojure/tools.logging "0.2.3"]                 
                 [ clj-logging-config "1.9.7"]
               
                 ])

Then, run lein deps to fetch these dependencies, and just add a line like the following to your code:

(ns my.namespace
  "Logging setup"
  (require [ clj-logging-config.log4j :as log-config]
           [ clojure.tools.logging :as log]))


(log-config/set-logger! :level :debug
                        :out (org.apache.log4j.FileAppender.
                              (org.apache.log4j.EnhancedPatternLayout. org.apache.log4j.EnhancedPatternLayout/TTCC_CONVERSION_PATTERN)
                              "logs/foo.log"
                              true))

(log/info "This is a test log message.")

This will get you started with some basic logging to logs/foo.log

If you want log rotation, use the DailyRollingFileAppender class instead of FileAppender. Many other setups are possible, too, such as logging to Syslog or logging to a socket. Take a look at the subclasses of AppenderSkeleton to get an idea of what’s there.

If you use the TTCC_CONVERSION_PATTERN as above, each line will automatically be prepended with the elapsed time since program start, thread name, severity, category, and “nested diagnostic context.” It’s easy to make your own prefix format; take a look at EnhancedPatternLayout for the options.

Check the clj-logging-config docs and its examples for more ideas. You may also need to delve into the Log4J JavaDocs.

Coming soon: how to colorize your logs.

Comments are closed.