2015-04-06 69 views
1

我正在使用pr-str来打印EDN以便与客户端进行字符串和通信。遇到非常有趣的行为,其中pr-str还输出混合到EDN字符串表示中的printlnclojure.tools.trace/trace消息。这是什么样的字符串pr-str输出:pr-str还打印出跟踪消息

(TRACE from-ds {:key "asdasf", :weight 0, :tag "1"} ; trace message 

{:key "asdasf", :weight 0, :tag "1"}) ; the actual edn that should be the sole output 

我似乎无法重现这个在REPL。

这是怎么发生的?如何解决它?

+0

'println' [有竞争条件](http://yellerapp.com/posts/2014-12-11-14-race-condition-in-clojure-println.html)? – 2015-04-06 11:09:00

+0

'print'(和扩展名'println')没有协调来防止重叠输出,但是只有当你的'pr-str'调用中的代码正在创建输出时,你才会得到这个结果。查看我的答案了解更多详情。 – noisesmith 2015-04-06 16:13:18

回答

2

pr-str使用with-out-str,它捕获块内发生的任何打印输出并将其转换为返回的字符串。

with-out-str创建*out*的线程本地绑定。正因为如此,您可能在输出字符串中获取日志输出的唯一方法是,如果pr-str调用中的代码正在进行日志记录。这可以通过绑定pr-str呼叫以外的值然后在该值上呼叫pr-str来解决。

例如。

(let [the-value (generate-some-value) ; this prints something 
     value-string (pr-str the-value)] ; this doesn't have trace output 
    ...)