如果您只是想禁用特定调用中发生的所有日志,您可以告诉 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)))))
这里还有改进、润色和优化空间,但看起来所有必要的组件都已经齐全,可以实现所需的函数。
我个人可能会倾向于将此类东西放入特定后端配置文件中,但这显然并不是您想要的。:)