如果你想简单地禁用特定调用中发生的所有日志记录,你可以告诉tools.logging使用提供的disabled-logger-factory
。
(require '[clojure.tools.logging :as log]
'[clojure.tools.logging.impl :as log-impl])
(binding [log/*logger-factory* log-impl/disabled-logger-factory]
(call-to-noisy-lib))
如果你想要根据消息的来源命名空间丢弃消息,
你可以创建自己的LoggerFactory
。
(def default-factory (log-impl/find-factory))
(def custom-factory
(reify log-impl/LoggerFactory
(name [_factory]
"some.arbitrary.name.for.this.factory")
(get-logger [factory logger-ns]
(if (= "namespace.you.want.to.silence" (str logger-ns))
log-impl/disabled-logger
(log-impl/get-logger default-factory logger-ns)))))
(binding [log/*logger-factory* custom-factory]
(call-to-noisy-lib))
如果你想根据消息的级别进行过滤,
你还需要实现一个自定义的记录器。
(defn logger-with-levels [wrapped-logger allowed-levels]
(reify log-impl/logger
(enabled? [logger level]
(when (contains? allowed-levels level)
(log-impl/enabled? wrapped-logger level)))
(write! [logger level throwable message]
(when (contains? allowed-levels level)
(log-impl/write! wrapped-logger level throwable message)))))
(def custom-factory
(reify log-impl/LoggerFactory
(name [_factory]
"some.arbitrary.name.for.this.factory")
(get-logger [factory logger-ns]
(if (= "namespace.you.want.to.silence" (str logger-ns))
(logger-with-levels (log-impl/get-logger default-factory logger-ns) #{:warn})
(log-impl/get-logger default-factory logger-ns)))))
这里还有提升、润色和优化的空间,但是看起来所有的必要部分都已经可用,以实现所需的功能。
个人来说,我会倾向于将这些内容放在特定后端配置文件中,但这显然不是您想要的。:)