用Clojure编写REST service 五 使用logback(有bug)

一个完整的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)


然后在src下面新建一个logback.xml

<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>


之后在src/my_website目录下创建log.clj文件,代码如下:(注意,这里定义了my-website.log namespace)

(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)))

现在可以在server.clj里面使用log了:(注意,这里引入了my-website.log namespace)

(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,看什么时候修复吧。

本文会在问题解决后更新。



你可能感兴趣的:(用Clojure编写REST service 五 使用logback(有bug))