一个完整的web app当然需要写日志。这里我采用习惯的slf4j+logback。
首先在my-website目录的project.clj文件中添加两个依赖:tools.logging&logback-classic
(defproject my-website "0.1.0-SNAPSHOT" :description "FIXME: write this!" :dependencies [[org.clojure/clojure "1.4.0"] [com.novemberain/monger "1.4.1"] [org.clojure/tools.logging "0.2.4"] [ch.qos.logback/logback-classic "1.0.7"] [noir "1.3.0-beta3"]] :main my-website.server)
<configuration debug="false"> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %-10contextName %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>/opt/web.log</file> <append>true</append> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <logger name="clojure-example-logback-integration" level="DEBUG"/> <root level="INFO"> <appender-ref ref="CONSOLE"/> <appender-ref ref="FILE"/> </root> </configuration>
(ns my-website.log (:require [clojure.tools.logging :as log])) (defn set-log-level! "Pass keyword :error :info :debug" [level] (let [logger (logimpl/get-logger log/*logger-factory* "clojure-logback-integration")] (case level :debug (.setLevel logger Level/DEBUG) :info (.setLevel logger Level/INFO) :error (.setLevel logger Level/ERROR)))) (defmacro debug [& args] `(log/debug (str ~@args))) (defmacro info [& args] `(log/info (str ~@args))) (defmacro warn [e & args] `(log/warn (str ~@args) ~e)) (defmacro warn [& args] `(log/warn (str ~@args))) (defmacro error [& args] `(log/error (str ~@args))) (defmacro error [e & args] `(log/error ~e (str ~@args)))
(ns my-website.server (:require [noir.server :as server]) (:require [my-website.log :as log])) (server/load-views-ns 'my-website.views) (server/load-views-ns 'my-website.rest.test) (defn -main [& m] (log/info "enter -main") (let [mode (keyword (or (first m) :dev)) port (Integer. (get (System/getenv) "PORT" "8080"))] (server/start port {:mode mode :ns 'my-website})))
不过很可惜,目前这个logback支持有bug,总是报找不到logimpl 。
我已经报了issue,看什么时候修复吧。
本文会在问题解决后更新。