<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Paul Legato &#187; clojure</title>
	<atom:link href="http://www.paullegato.com/blog/tag/clojure/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.paullegato.com</link>
	<description></description>
	<lastBuildDate>Tue, 06 Dec 2011 00:52:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Swing-Clojure GUI for the Black-Scholes Option Modeler</title>
		<link>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/</link>
		<comments>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 07:55:56 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[finance]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=352</guid>
		<description><![CDATA[Now that we have implemented Black-Scholes in Clojure, let&#8217;s make a Swing GUI for it. The Swing GUI will have text boxes for all the necessary inputs, and calculate prices and Greeks when the button is pressed. It&#8217;s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here&#8217;s what it [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we have implemented <a href="http://www.paullegato.com/blog/black-scholes-clojure/" >Black-Scholes in Clojure</a>, let&#8217;s make <a target="_blank" href="http://github.com/pjlegato/clojure_options" >a Swing GUI for it</a>. The Swing GUI will have text boxes for all the necessary inputs, and calculate prices and Greeks when the button is pressed. It&#8217;s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here&#8217;s what it looks like. <a href="http://www.paullegato.com/wp-content/uploads/2010/07/Swing-GUI-Clojure-Black-Scholes.png" ><img src="http://www.paullegato.com/wp-content/uploads/2010/07/Swing-GUI-Clojure-Black-Scholes.png" alt="Screenshot of the Swing GUI for the Black-Scholes option modeler, implemented in Clojure" title="Swing-GUI-Clojure-Black-Scholes" width="569" height="355" class="alignright size-full wp-image-354" /></a></p>
<p>The GUI is written entirely in Clojure with the Swing toolkit. Calculation state is stored in a series of atoms. Watches are used to update the output table automatically when an atom changes, <a target="_blank" href="http://kotka.de/blog/2010/05/Decoupling_Logic_and_GUI.html" >an idea from Kotka</a>. I used the excellent <a target="_blank" href="http://www.miglayout.com/" >MiG Layout</a> for general layout functionality, and generic Swing widgets (JTextFields and a JTable) for the input and output.<br />
<span id="more-352"></span></p>
<h2>Clojure code</h2>
<p>The Black-Scholes GUI is launched with the<code>main</code> function. The Swing GUI is actually created in the <code>initialize-gui</code> function, but since <a target="_blank" href="http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html" >Swing widgets are not threadsafe</a>, we must use the <code>do-swing*</code> helper function from Clojure Contrib to spin off the real GUI creation code into the Swing event thread.</p>
<pre class="brush: clojure; title: ; notranslate">
(defn initialize-gui
  []
  (let [frame (JFrame. &quot;Black-Scholes Option Modeler&quot;)]

    (doto frame
      (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
      (-&gt; .getContentPane
          (.add (miglayout (JPanel.)

                           (input-panel
                            (fn [_]
                              (do-swing
                               (doto frame
                                 (.setVisible false)
                                 (.dispose)))))

                           (result-table)

                           )))

      (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
      (.pack)
      (.setVisible true))
     ))

(defn main
  []
  (do-swing* :now initialize-gui))
</pre>
<p>This is pretty straightforward. We make a (locally scoped) JFrame to be the main container at line 3. Within the context of the <code>let</code>, we add a JPane using MiG Layout to its content area (starting at line 8). The JPanel itself contains two subwidgets, which are those returned from the <code>input-panel</code> and <code>result-table</code> functions.</p>
<p>Note that we are passing an anonymous function to <code>input-panel</code> at line 11. The input panel contains the &#8220;Quit&#8221; button, and that button needs to know what to do when it&#8217;s pressed. We want it to close the GUI; that is, it should destroy the outer JFrame. To do that, it needs a reference to it. However, as a local variable in <code>initialize-gui</code>, the JFrame is not in scope elsewhere; we have to pass it in. The given function closes over the JFrame reference (line 13) and transports it to <code>input-panel</code>, where that function will be called as an event listener when the &#8220;Quit&#8221; button is pressed.</p>
<p>We could also have simply passed the bare JFrame rather than a function, and moved the frame-closing code into <code>input-panel</code>, but that would imply that the input panel must always be in a JFrame, which will not necessarily the case. Passing in an external anonymous function to be activated by the &#8220;Quit&#8221; button allows the input panel to be used generically in any sort of container, with the container deciding what to do when &#8220;Quit&#8221; is pressed.</p>
<h3>The Input Panel</h3>
<pre class="brush: clojure; title: ; notranslate">

(defn- input-panel [quit-action]
    (let [
          ;; Fields
          spot (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                 (.setColumns 6)
                 (.setValue @*spot*))

          strike (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                   (.setColumns 6)
                   (.setValue @*strike*))

          days-till-expiry (doto (JFormattedTextField. (NumberFormat/getIntegerInstance))
                             (.setColumns 6)
                             (.setValue @*days-till-expiry*))

          riskfree (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                     (.setColumns 6)
                     (.setValue @*riskfree*))

          volatility (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                       (.setColumns 6)
                       (.setValue @*volatility*))

          ;; Buttons
          calculate (JButton. &quot;Calculate&quot;)
          quit (JButton. &quot;Quit&quot;)
          ]

      (add-action-listener
       calculate
       (fn [_]
         (update-all-calculations
          (Double/parseDouble (.getText spot))
          (/ (Integer/parseInt (.getText days-till-expiry)) *trading-days-per-year*)
          (Double/parseDouble (.getText strike))
          (Double/parseDouble (.getText riskfree))
          (Double/parseDouble (.getText volatility)))))

      (add-action-listener
       quit
       quit-action)

      (miglayout (JPanel.)
                 :layout  [:wrap 2 ]

                 (JLabel. &quot;Spot&quot;) [:align &quot;right&quot;]
                 spot

                 (JLabel. &quot;Strike&quot;) [:align &quot;right&quot;]
                 strike

                 (JLabel. &quot;Risk-free rate&quot;) [:align &quot;right&quot;]
                 riskfree

                 (JLabel. &quot;Volatility&quot;) [:align &quot;right&quot;]
                 volatility

                 (JLabel. &quot;Days till expiry&quot;) [:align &quot;right&quot;]
                 days-till-expiry

                 calculate
                 quit)))
</pre>
<p>The input widgets are local variables in the input panel function, along with the two buttons. The widgets are initialized from the state atoms (which are then unused again; see discussion below.) The &#8220;Quit&#8221; button is given the event callback passed in as an argument (so it can manipulate the enclosing JFrame as per above.) The &#8220;Calculate&#8221; button is given an event callback that calls the <code>update-all-calculations</code> function with the values in the input widgets.</p>
<p>The lot are then stuffed into a JPanel with a MiG Layout and returned.</p>
<h3>The Output Table</h3>
<pre class="brush: clojure; title: ; notranslate">
(defn- update-cell
  &quot;Updates the given AbstractTableModel cell and fires a change event for that cell.&quot;
  [model data row col]
  (.setValueAt model data row col)
  (.fireTableCellUpdated model row col))

(defn- result-table []
  (let [
        column-names [&quot;&quot; &quot;Call&quot; &quot;Put&quot;]
        row-names [&quot;Price&quot; &quot;Delta&quot; &quot;Theta&quot; &quot;Rho&quot; &quot;Gamma&quot; &quot;Vega&quot;]
        table-model (proxy [AbstractTableModel] []
                      (getColumnCount [] (count column-names))
                      (getRowCount [] (count row-names))
                      (isCellEditable [] false)
                      (getColumnName [col] (nth column-names col))
                      (getValueAt [row col]
                                  (condp = col
                                      0 (nth row-names row) ;; Return the row name for column zero
                                      (condp = [row col]
                                          [0 1] @*call-price*
                                          [0 2] @*put-price*

                                          [1 1] @*call-delta*
                                          [1 2] @*put-delta*

                                          [2 1] @*call-theta*
                                          [2 2] @*put-theta*

                                          [3 1] @*call-rho*
                                          [3 2] @*put-rho*

                                          [4 1] @*gamma*
                                          [4 2] &quot;==&quot;

                                          [5 1] @*vega*
                                          [5 2] &quot;==&quot;

                                          nil))))

        table (doto (JTable. table-model)
                (.setGridColor java.awt.Color/DARK_GRAY))
        ]

    (add-watch *call-price* ::update-call-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 1)))
    (add-watch *put-price* ::update-put-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 2)))

    (add-watch *call-delta* ::update-call-delta (fn [_ _ _ newval] (update-cell table-model newval 1 1)))
    (add-watch *put-delta* ::update-put-delta (fn [_ _ _ newval] (update-cell table-model newval 1 2)))

    (add-watch *call-theta* ::update-call-theta (fn [_ _ _ newval] (update-cell table-model newval 2 1)))
    (add-watch *put-theta* ::update-put-theta (fn [_ _ _ newval] (update-cell table-model newval 2 2)))

    (add-watch *call-rho* ::update-call-rho (fn [_ _ _ newval] (update-cell table-model newval 3 1)))
    (add-watch *put-rho* ::update-put-rho (fn [_ _ _ newval] (update-cell table-model newval 3 2)))

    (add-watch *gamma* ::update-gamma (fn [_ _ _ newval] (update-cell table-model newval 4 1)))
    (add-watch *vega* ::update-vega (fn [_ _ _ newval] (update-cell table-model newval 5 1)))

    ;; This shrinks the table's preferred viewport down to its actual size.
    ;; (The default is to make a huge viewport, even though the table is small.)
    (.setPreferredScrollableViewportSize table (.getPreferredSize table))

    (JScrollPane. table)
    ))
</pre>
<p>The output table itself is a standard JTable. Its model is initialized from the output state atoms. The watches at lines 44-57 are the most interesting part; they allow arbitrary code to be called when the output state atoms change. This allows the Black-Scholes calculation to happen independently of the output widget. When one of those atoms is changed, it self-updates automatically via the watches.</p>
<p>The helper function at lines 1-5 updates the appropriate model cell and fires an event to tell the JTable to repaint it.</p>
<p>The scrollable viewport business at line 61 is to work around a questionable Java design decision where a JTable, by default, tells its container to make its viewport enormous, even though it have very little data. (That&#8217;s not an error, that&#8217;s subjunctive.)</p>
<h2>Design considerations</h2>
<h3>GUI and business logic decoupling</h3>
<p>Above all, the GUI has to be decoupled from the model itself. Internal changes to one should never affect the other, and the two should be independently testable. In such a simple application, this was easy enough. A more complex app that requires several information round trips would be trickier. We now have a good foundation for such an app. No business calculations are performed in the GUI code namespace. The sole point of connection is in the update-all-calculations function:</p>
<pre class="brush: clojure; title: ; notranslate">

(defn- update-all-calculations [spot timeleft strike riskfree sigma]
  (swap! *call-price* (fn [_] (bs/call spot timeleft strike riskfree sigma)))
  (swap! *put-price* (fn [_] (bs/put spot timeleft strike riskfree sigma)))

  (swap! *call-delta* (fn [_] (bs/call-delta spot timeleft strike riskfree sigma)))
  (swap! *put-delta* (fn [_] (bs/put-delta spot timeleft strike riskfree sigma)))

  (swap! *call-theta* (fn [_] (bs/call-theta spot timeleft strike riskfree sigma)))
  (swap! *put-theta* (fn [_] (bs/put-theta spot timeleft strike riskfree sigma)))

  (swap! *call-rho* (fn [_] (bs/call-rho spot timeleft strike riskfree sigma)))
  (swap! *put-rho* (fn [_] (bs/put-rho spot timeleft strike riskfree sigma)))

  (swap! *vega* (fn [_] (bs/vega spot timeleft strike riskfree sigma)))
  (swap! *gamma* (fn [_] (bs/gamma spot timeleft strike riskfree sigma))))
</pre>
<h3>Atoms to hold state</h3>
<p>As we can see above, set of atoms holds state for the GUI, in keeping with the general Clojure principle of isolating state into transactional memory. (Actually, I cheated a bit. Our full state consists of the input values and the results of our Black-Scholes calculations. Although I created atoms for the input state values as well, I calculate the results directly from the widgets. It is a trivial exercise to alter the &#8220;Calculate&#8221; button callback to use the atoms. This would be more useful in the case where changes to a widget fire an event that triggers recalculation, which is not done in this demo as per below. I would use the atoms in a real application.)</p>
<p>I/O is inherently stateful, as are GUIs. There was therefore the temptation to use the Swing widget objects themselves as state-holders, and in fact it requires extra code to shuttle data back and forth between the widgets and the atoms. In such a simple app as this, using the GUI widgets as state-holders does not make much practical difference, but in a more complex app, a well designed set of state atoms and watches can automate much of the tedious GUI logic.</p>
<p>Using the widgets directly as state holders implies a tight coupling between the input widgets, the business logic, and the output widgets. Changing any one of them would invariably have required changes to the linking logic.</p>
<p>For example, suppose we were using widgets-as-state, and we changed the &#8220;days left till expiry&#8221; input to a slider rather than a text box, or suppose we wanted to read it from a file or from an API. We would have to update the code that reads it, calculates the model, and puts the results into the output table. Touching that code implies a non-zero likelihood of breaking it. Why even introduce the potential for breaking something that is unrelated to the task at hand, in this case the business logic and output code?</p>
<p>Again, this seems trivial with such a very small application that is only a few lines long, but the design principle is what&#8217;s important. Imagine applying it to a much larger application with hundreds of inputs spread across 4 windows, 3 databases, and 6 web feeds to see why this is a good idea.</p>
<h3>Auto-updating results when input changes</h3>
<p>I wanted the results to auto-update anytime an input is changed, without resorting to a &#8220;Calculate&#8221; button. Having the button trigger the calculation and output update allows the state of the input and the output to become decoupled, which can be confusing for the user. Worse, it could be unnoticed by a user who is doing other things at the same time.</p>
<p>Due to typical Java overengineering, there is no straightforward way to simply <code>(add-action-listener)</code> on the JTextField and get notifications when it changes. Instead, <a target="_blank" href="http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/generaltext.html#document" >each Swing widget implements full-blown model-view separation</a>, and so you have to get the document underlying the JTextField. Yes, the view components of your MVC application themselves contain both models and views. Each and every field contains an entire implementation of the document object and associated cruft, all for itself. If you want to monitor changes in the widget, you need to build out a <code>DocumentListener</code> to watch for such events.</p>
<p>In a real application, I&#8217;d bite the bullet and implement it, but it&#8217;s not worth the extra time for the purposes of this demo, so we are left with a &#8220;Calculate&#8221; button and manual updating.</p>
<h2>Clojure-Options on Github</h2>
<p>The entire package so far is now <a target="_blank" href="http://github.com/pjlegato/clojure_options" >available on my GitHub page</a>. Patches are welcome. Atomizing the input widgets and adding the appropriate event callbacks and watches to eliminate the &#8220;Calculate&#8221; button is particularly welcome. <img src='http://www.paullegato.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=352&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Black-Scholes in Clojure</title>
		<link>http://www.paullegato.com/blog/black-scholes-clojure/</link>
		<comments>http://www.paullegato.com/blog/black-scholes-clojure/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 00:51:27 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[finance]]></category>
		<category><![CDATA[quant]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=345</guid>
		<description><![CDATA[The Black-Scholes option pricing model, implemented in Clojure based on the description at Wikipedia and these code samples. This code uses the new Incanter Distributions module, which hasn&#8217;t been released yet, so it requires the latest master version from Github. Most of the values agree with those produced at BloBek&#8217;s calculator, with the exception of [...]]]></description>
			<content:encoded><![CDATA[<p>The Black-Scholes option pricing model, implemented in Clojure based on <a target="_blank" href="https://secure.wikimedia.org/wikipedia/en/wiki/Black–Scholes" >the description at Wikipedia</a> and <a target="_blank" href="http://www.espenhaug.com/black_scholes.html" >these code samples</a>.<br />
<span id="more-345"></span></p>
<pre class="brush: clojure; title: ; notranslate">
;;
;; Black-Scholes option pricing model
;;
;; Copyright (C) 2010 Paul Legato. All rights reserved.
;; Licensed under the New BSD License. See the README file for details.
;;
;; Disclaimer: This code comes with NO WARRANTY, express or implied.
;; There may be any number of bugs. Use at your own risk.
;;
;; References:
;; - https://secure.wikimedia.org/wikipedia/en/wiki/Black%E2%80%93Scholes
;; - http://www.espenhaug.com/black_scholes.html

(ns clojure-options.black-scholes
  (:require incanter.distributions))

(defn d1
  [spot timeleft strike riskfree sigma]
  (/
   (+ (Math/log (/ spot strike))
      (* (+ riskfree (/ (* sigma sigma) 2))
         timeleft))
   (* sigma (Math/sqrt timeleft))))

(defn d2
  [spot timeleft strike riskfree sigma]
  (- (d1 spot timeleft strike riskfree sigma) (* sigma (Math/sqrt timeleft))))

(defn- n [val] (incanter.distributions/cdf (incanter.distributions/normal-distribution) val))

(defn call
  &quot;Returns the theoretic value of a European call option on the given underlying based on the Black-Scholes model.

 * spot - spot price of the underlying
 * timeleft - time to expiration, in years
 * strike - option strike price
 * riskfree - annual continuous risk-free interest rate
 * sigma - volatility of the underlying

&quot;
  [spot timeleft strike riskfree sigma]
  (- (* spot (n (d1 spot timeleft strike riskfree sigma)))
     (* strike
        (Math/exp (* (- riskfree) timeleft))
        (n (d2 spot timeleft strike riskfree sigma)))))

(defn put
  &quot;Returns the theoretic value of a European put option on the given underlying based on the Black-Scholes model.

 * spot - spot price of the underlying
 * timeleft - time to expiration, in years
 * strike - option strike price
 * riskfree - annual continuous risk-free interest rate
 * sigma - volatility of the underlying

&quot;
  [spot timeleft strike riskfree sigma]
  (- (* strike
        (Math/exp (* (- riskfree) timeleft))
        (n (- (d2 spot timeleft strike riskfree sigma))))
     (* spot (n (- (d1 spot timeleft strike riskfree sigma))))))

(defn call-delta
  [spot timeleft strike riskfree sigma]
  (n (d1 spot timeleft strike riskfree sigma)))

(defn put-delta
  [spot timeleft strike riskfree sigma]
  (- (n (d1 spot timeleft strike riskfree sigma)) 1))

(defn- nprime [val] (incanter.distributions/pdf (incanter.distributions/normal-distribution) val))

(defn gamma
  [spot timeleft strike riskfree sigma]
  (/ (nprime (d1 spot timeleft strike riskfree sigma))
     (* spot sigma (Math/sqrt timeleft))))

(defn vega
  [spot timeleft strike riskfree sigma]
  (* spot (nprime (d1 spot timeleft strike riskfree sigma)) (Math/sqrt timeleft)))

(defn call-theta
  [spot timeleft strike riskfree sigma]
  (-
   (- (/ (* spot (nprime (d1 spot timeleft strike riskfree sigma)) sigma)
         (* 2 (Math/sqrt timeleft))))
   (* riskfree strike (Math/exp (* (- riskfree) timeleft)) (n (d2 spot timeleft strike riskfree sigma)))))

(defn put-theta
  [spot timeleft strike riskfree sigma]
  (-
   (- (/ (* spot (nprime (d1 spot timeleft strike riskfree sigma)) sigma)
         (* 2 (Math/sqrt timeleft))))
   (* riskfree strike (Math/exp (* (- riskfree) timeleft)) (n (- (d2 spot timeleft strike riskfree sigma))))))

(defn call-rho
  [spot timeleft strike riskfree sigma]
  (* strike timeleft (Math/exp (* (- riskfree) timeleft)) (n (d2 spot timeleft strike riskfree sigma))))

(defn put-rho
  [spot timeleft strike riskfree sigma]
  (* (- strike) timeleft (Math/exp (* (- riskfree) timeleft)) (n (- (d2 spot timeleft strike riskfree sigma)))))
</pre>
<p>This code uses the new <a target="_blank" href="http://liebke.github.com/incanter/distributions-api.html" >Incanter Distributions module</a>, which hasn&#8217;t been released yet, so it requires the latest master version from Github.</p>
<p>Most of the values agree with those produced at <a target="_blank" href="http://www.blobek.com/black-scholes.html"  class="broken_link">BloBek&#8217;s calculator</a>, with the exception of theta. I imagine this has to do with the units used for the &#8220;days left to expiration&#8221; field; my calculator uses fractions of a year, while BloBek doesn&#8217;t specify whether his days are to be trading days or calendar days. It could also be a bug in one of our implementations.</p>
<p>In Part 2, I&#8217;ll build a simple Swing GUI for the calculator.<br />
<b>Update:</b> <a href="http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/" >Part 2, with the Swing GUI</a>, is now available. You can also get <a target="_blank" href="http://github.com/pjlegato/clojure_options" >the entire project&#8217;s source code</a> from GitHub.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=345&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/black-scholes-clojure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Lazy-spy: Clojure logging/spy for lazy sequences</title>
		<link>http://www.paullegato.com/blog/lazy-spy-clojure-logging-lazy-sequences/</link>
		<comments>http://www.paullegato.com/blog/lazy-spy-clojure-logging-lazy-sequences/#comments</comments>
		<pubDate>Mon, 24 May 2010 02:27:16 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=315</guid>
		<description><![CDATA[Clojure.contrib's log/spy macro does not realize the contents of lazy sequences by default when logging, as they might be infinitely long. If you're sure that your lazy sequence is finite, you can use this lazy-spy macro to force it to be realized when it's logged, so that you can inspect the contents.]]></description>
			<content:encoded><![CDATA[<p>Clojure.contrib&#8217;s <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html#clojure.contrib.logging/spy" ><code>logging/spy</code> macro</a> is really useful for quick investigation of bugs with unclear stack traces, and to check that intermediate values in a calculation are being returned and composed correctly. Lazy sequences don&#8217;t get logged correctly, however:</p>
<pre class="brush: clojure; title: ; notranslate">
&gt; (log/spy [1 2 3 4 5])
[1 2 3 4 5] ;;; prints &quot; [1 2 3 4 5] =&gt; [1 2 3 4 5]&quot; to the log
&gt; (log/spy (take 3 [1 2 3 4 5]))
(1 2 3) ;;; prints &quot;(take 3 [1 2 3 4 5]) =&gt; clojure.lang.LazySeq@8592&quot; to the log
</pre>
<p>The <code>spy</code> macro logs a string realization of the sequence per se, rather than its constituents. In the case of a concrete, fully realized sequence such as the literal vector in the first example, all values are known in advance, and the vector&#8217;s string realization in the log can helpfully be its actual contents. In the case of the lazy sequence returned by <code>take</code>, however, we get a less than helpful class name and some sort of instance identifier code rather than the actual contents of the sequence. A lazy sequence saves resources by merely promising to provide the values when asked. If they&#8217;re never asked for, they&#8217;re never computed. Since they haven&#8217;t been computed, they can&#8217;t be printed. A lazy sequence can also potentially be infinitely long, another good reason why they are not realized by default when converting the sequence to a string.</p>
<p>In our case, we don&#8217;t care about the resource usage, and we&#8217;re sure the sequence is finite. We want to force all values to be computed for manual inspection. (There are <a target="_blank" href="http://stackoverflow.com/questions/1641626/how-to-covert-a-lazy-sequence-to-a-non-lazy-in-clojure" >several ways of going about this</a>.) The following modification of the <code>spy</code> macro converts the lazy sequence into a regular seq:</p>
<pre class="brush: clojure; title: ; notranslate">
(defmacro lazy-spy
  &quot;Evaluates expr and outputs the form and its result to the debug log.
   If the result is a lazy sequence, it is realized concretely in the log.
   Returns the result of expr.&quot;
  [expr]
  `(let [a# ~expr] (log/log :debug (str '~expr &quot; =&gt; &quot;
                                    (if (= clojure.lang.LazySeq (class a#))
                                      (seq a#)
                                       a#)))
        a#))
</pre>
<p>This gives us:</p>
<pre class="brush: clojure; title: ; notranslate">
&gt; (lazy-spy  (take 3 [1 2 3 4 5]))
(1 2 3) ;;; prints &quot;(take 3 [1 2 3 4 5]) =&gt; (1 2 3)&quot; to the log
</pre>
<h2>Clojure posts you might also like:</h2>
<ul>
<li><a href="http://www.paullegato.com/blog/log4j-clojure/" >Log4J and Clojure Configuration</a></li>
<li><a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >Setting Clojure’s Log Level</a></li>
<li><a href="http://www.paullegato.com/blog/sql-where-clojure-s-expressions/" >SQL WHERE clauses in Clojure from S-Expressions</a>
<li><a href="http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/" >XML DTD Validation in Clojure: Turning It Off, Parsing Malformed XML</a></li>
</ul>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=315&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/lazy-spy-clojure-logging-lazy-sequences/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Log4J and Clojure Configuration</title>
		<link>http://www.paullegato.com/blog/log4j-clojure/</link>
		<comments>http://www.paullegato.com/blog/log4j-clojure/#comments</comments>
		<pubDate>Sun, 16 May 2010 22:12:48 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=292</guid>
		<description><![CDATA[Clojure, Log4J, and clojure.contrib.logging can play nicely together. Here's a reasonable default configuration.]]></description>
			<content:encoded><![CDATA[<p>Clojure, Log4J, and <code>clojure.contrib.logging</code> can play nicely together. Here&#8217;s a reasonable default configuration.</p>
<ol>
<li>
<p>If using <a target="_blank" href="http://github.com/technomancy/leiningen" >Leiningen</a>, add</p>
<pre class="brush: clojure; title: ; notranslate">
:dependencies [
                 [log4j &quot;1.2.15&quot; :exclusions [javax.mail/mail
                                              javax.jms/jms
                                              com.sun.jdmk/jmxtools
                                              com.sun.jmx/jmxri]]
]
</pre>
<p>to your <code>project.clj</code> file and rerun <code>lein deps</code> to auto-install the Log4J JAR.
</p>
<p>If not using Leiningen, <a target="_blank" href="http://logging.apache.org/log4j/1.2/download.html" >acquire a Log4J JAR</a> and put it on your classpath.</p>
</li>
<li>Create a file called <code>log4j.properties</code> on your classpath and put the following into it:
<pre class="brush: plain; title: ; notranslate">
# Based on the example properties given at http://logging.apache.org/log4j/1.2/manual.html
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern= %-5p %c - %m%n
</pre>
</li>
</ol>
<p>That&#8217;s the short version. Read on for the gory details.<span id="more-292"></span></p>
<h2>Logging philosophy</h2>
<p>My logging requirements are simple at the moment. I want to write messages to the console, each tagged with a log level (&#8220;INFO&#8221;, &#8220;WARN&#8221;, &#8220;ERROR&#8221;, etc.) I want to be able to set a log level, and only see log messages of that severity or higher. That&#8217;s it. I take this to be the canonical base case of logging that covers 80% of needs. All other logging features (e.g. logging to a file, differentiating by class or namespace) are nice, but much less common, and ought to be handled via configurable deviations from this default case.</p>
<p><code>clojure.contrib.logging</code> does not presently make it easy to do any of this common base case out of the box. The Lispy façade quickly falls apart; you&#8217;re <a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >dumped into the deep end of the Java overengineering mire</a> without a life vest when you simply want to change the log level temporarily. </p>
<h3>What&#8217;s wrong with clojure.contrib.logging&#8217;s defaults?</h3>
<p><code>clojure.contrib.logging</code> with no special configuration done prefaces each and every logged line on my system with:</p>
<pre class="brush: plain; title: ; notranslate">
[null] May 16, 2010 1:08:48 PM clojure.contrib.logging$eval__2077$impl_write_BANG___2088 invoke
</pre>
<p>I have no idea why. This makes it very hard to read the log when logging any nontrivial amount of information.</p>
<p><a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html" >clojure.contrib.logging&#8217;s documentation</a> contains a rather cryptic offhanded remark, with no further explanation: <em>Note: your log configuration should display the name that was passed to the logging implementation, and not perform stack-inspection, otherwise you&#8217;ll see something like &#8220;fn__72$impl_write_BANG__39__auto____81&#8243; in your logs.</em></p>
<p>My log configuration? Stack inspection? Why do I need to have a log configuration to just dump strings to the console? Why is the default case to print a verbose and useless header for each line? Isn&#8217;t this Javaesque mess &mdash; <a target="_blank" href="http://wiki.apache.org/logging-log4j/Log4jXmlFormat" >obscure 50 line XML configuration files just to get basic logging functionality working</a> &mdash; exactly what we&#8217;re trying to avoid?</p>
<h2>Log4J with <code>clojure.contrib.logging</code> configuration</h2>
<p>Ah, well, there&#8217;s nothing for it, I suppose.  Better just get a serious logging library and figure out how to configure it. The docs say that <code>clojure.contrib.logging</code> delegates to the first supported logging implementation that it finds. I am apparently using <a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >the builtin JDK logger</a> by default, and Apache Commons&#8217; logger is just another wrapper, so I added Log4J to Leiningen&#8217;s project.clj and it installed the jar for me.</p>
<p>Now, I get:</p>
<pre class="brush: plain; title: ; notranslate">
     [null] log4j:WARN No appenders could be found for logger (my-project-name).
     [null] log4j:WARN Please initialize the log4j system properly.
</pre>
<p>Followed by dead silence.</p>
<p>Hm.</p>
<p>I can only imagine that Log4j was never intended to be used without a custom configuration. Odd. Why people design software that comes without reasonable defaults pre-set to cover the common base case is beyond me. I fully understand that strange setups will require customized configuration, but &#8220;dumping strings to the console&#8221; does not seem like a bizarre edge case for a logging package. A default case of &#8220;send all log messages to the black hole unless configured to do otherwise&#8221; makes little sense.</p>
<p>So, how hard can it be to configure Log4J for this base case functionality? The &#8220;<a target="_blank" href="http://logging.apache.org/log4j/1.2/manual.html" >short introduction to log4j</a>&#8221;  is 19 pages long. Sigh. (<a target="_blank" href="http://www.qos.ch/shop/products/log4jManual" >The complete manual</a> is proudly described as &#8220;over 200 pages.&#8221; I sometimes wonder if they overengineer Java libraries on purpose just to drive book sales.) </p>
<p>I do not want to know what a Nested Diagnostic Context is, or the precise semantic distinction between &#8220;Loggers,&#8221; &#8220;Appenders,&#8221; and &#8220;Layouts.&#8221; I don&#8217;t care about &#8220;Appender Additivity&#8221; and &#8220;Named Hierarchies,&#8221; and I certainly don&#8217;t want to write an XML configuration file. I Just want to log tagged strings to the console, and have them print without a bizarre autogenerated header line. That&#8217;s it. I fully appreciate that those things will be useful for some people &mdash; maybe even for me, when my project grows to become more complex. I have nothing against their existence; but for the base case, one should not need to know of it.</p>
<p>On page 9 of the &#8220;short&#8221; manual, after a boatload of irrelevant information, we have an answer: there is a class called <code>BasicConfigurator</code> with a static method that does reasonable initialization for logging to the console. We can just do <code>(org.apache.log4j.BasicConfigurator/configure)</code> and get that.</p>
<p>However, we are still getting log messages like:</p>
<pre class="brush: plain; title: ; notranslate">
     [null] 3702 [8633270@qtp-3149669-2] INFO my.namespace - log message
</pre>
<p>We have to learn something about <a target="_blank" href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/EnhancedPatternLayout.html" >Layouts</a> now. The thread names generated by Clojure are apparently not very useful, so we&#8217;re going to turn them off. And while interesting when profiling, the number of milliseconds since program start is just going to be visual clutter 98% of the time, so I&#8217;m going to turn that off, too, until I actually need it.</p>
<p>The result is the <code>log4j.properties</code> file listed above. Just copy and paste it into your classpath. If you want more or different information in your logs, take a look at the <a target="_blank" href="http://logging.apache.org/log4j/1.2/apidocs/index.html?org/apache/log4j/PatternLayout.html" >PatternLayout API documentation</a> and alter the <code>ConversionPattern</code> line according to your preferences.</p>
<p>The result:</p>
<pre class="brush: plain; title: ; notranslate">
     [null] INFO  my.namespace - log message
</pre>
<p>I&#8217;m still not sure where the <code>[null]</code> comes from, but overall, it&#8217;s very readable.</p>
<h2>Clojure posts you might also like:</h2>
<ul>
<li><a href="http://www.paullegato.com/blog/lazy-spy-clojure-logging-lazy-sequences/" >Lazy-spy: Clojure logging/spy for lazy sequences</a></li>
<li><a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >Setting Clojure’s Log Level</a></li>
<li><a href="http://www.paullegato.com/blog/sql-where-clojure-s-expressions/" >SQL WHERE clauses in Clojure from S-Expressions</a>
<li><a href="http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/" >XML DTD Validation in Clojure: Turning It Off, Parsing Malformed XML</a></li>
</ul>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=292&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/log4j-clojure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>XML DTD Validation in Clojure: Turning It Off, Parsing Malformed XML</title>
		<link>http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/</link>
		<comments>http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 00:29:31 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sax]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=262</guid>
		<description><![CDATA[I wanted to parse some externally-generated and malformed HTML, so naturally I went to the short and sweet clojure.xml/parse function. I got a nasty error: error: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd It seems that the W3C blocked access to the DTDs two years ago, but Java still tries to load [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to parse some externally-generated and malformed HTML, so naturally I went to the short and sweet <a target="_blank" href="http://richhickey.github.com/clojure/clojure.xml-api.html" ><code>clojure.xml/parse</code> function</a>. I got a nasty error:</p>
<blockquote><p>
<code>error: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</code>
</p></blockquote>
<p>It seems that <a target="_blank" href="http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic" >the W3C blocked access to the DTDs</a> two years ago, but Java still tries to load them by default anyway. The following allows <code>clojure.xml</code> to run without checking external DTDs:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn startparse-sax-non-validating [s ch]
  (.. (doto (. javax.xml.parsers.SAXParserFactory (newInstance))
       (.setValidating false)
       (.setFeature &quot;http://apache.org/xml/features/nonvalidating/load-dtd-grammar&quot; false)
       (.setFeature &quot;http://apache.org/xml/features/nonvalidating/load-external-dtd&quot; false)
       (.setFeature &quot;http://xml.org/sax/features/validation&quot; false)
       (.setFeature &quot;http://xml.org/sax/features/external-general-entities&quot; false)
       (.setFeature &quot;http://xml.org/sax/features/external-parameter-entities&quot; false))

       (newSAXParser) (parse s ch))))
</pre>
<p>Then you can simply <code>(xml/parse "sourcefile.xml" startparse-sax-non-validating)</code>. This is not the ideal solution &mdash; ideally, we want to use a locally cached DTD &mdash; but it works well enough for one-off code. Read on for further information.<span id="more-262"></span></p>
<h2>W3C&#8217;s malformed specification</h2>
<p>The W3C webserver was being DDoSed by the massive number of XML parsers trying to download the DTDs constantly, so they just blocked everyone. This is a direct result of the poorly considered technical specification for DTD identification and <a target="_blank" href="http://en.wikipedia.org/wiki/URI#Relationship_to_URL_and_URN" >URIs themselves</a>, then exacerbated by the W3C&#8217;s institutional culture and philosophy.</p>
<h3>Technical commentary</h3>
<p>The root of the problem is, as they put it, that &#8220;these [DTD URIs] are <em>not hyperlinks</em>; these URIs are used for identification&#8221; (emphasis in original.) This is an abuse of the URL format. If it&#8217;s &#8220;for identification,&#8221; then it doesn&#8217;t need to specify a transport protocol! They are relying upon their particular interpretation of the old <a target="_blank" href="http://tools.ietf.org/html/rfc3305" >URI/URL debate</a>, reducing the transport protocol element to a namespace identifier instead, and then assuming everyone will defer to their judgement and wisdom on the matter.</p>
<p>The W3C (and others who share their URL/URI interpretation) decided to conflate the semantic functions of <em>locating and transporting</em> a resource with the very distinct function of <em>identifying</em> a resource. &#8220;My name&#8221; is not the same thing as an instruction to &#8220;get in your car, drive to my street address, pick up someone with my name here, and then drive me back to your house,&#8221; even though there is indeed only one person with my name at this address. If you want to identify me, you would not give someone the latter instruction. Most likely, they didn&#8217;t think about this at all and just did it. Now everyone suffers for this poor design decision. They are being DDoSed and paying massive amounts of money to keep the servers going, and everyone&#8217;s XML parsers are broken because they&#8217;re now returing 503s for all the DTD URIs.</p>
<p>The W3C&#8217;s proposed solution is that everyone else should a) defer to their views on the URL/URI matter, and 2) rewrite their XML parsers to be massively more complex and build local caching DTD catalogs for every single one-off parse. In practice, most people will just turn DTD validation off, potentially breaking a lot of other things.</p>
<h3>Institutional commentary on the W3C itself</h3>
<p>The tone of naive incredulity in the W3C&#8217;s plea is most amazing of all. They seem genuinely baffled as to why anyone would ever choose to ignore their wisdom on the URL/URI matter, and even more confused as to how anyone could ignore any detail of a baroque and poorly communicated specification like those for XML and DTD cataloging. &#8220;We spent a long time writing that, and we have [the self-appointed] institutional authority to write specifications and make determinations like what a URI should be, so surely people would never just ignore us!&#8221;</p>
<p>For them, the only conceivable explanation for every detail of the specification not being implemented is sheer ignorance. They even gently chide the readers about their failure to use URIs properly and to build DTD caches into everything, much as a kindergarten teacher would a well-meaning but rather dumb child who continually ignores instructions about how to use his crayons. They think that they only have to patiently remind people enough times that there is indeed a right way to do it, that which is sanctioned by the appropriate institutional authorities (them, of course) &mdash; and finally everything will be fine once people get that message.</p>
<p>This is the sort of ingenuous attitude that can only develop in a pure research institute and among people who mostly have very high <a target="_blank" href="http://psychology.wikia.com/wiki/Power_distance" >power distance index scores</a>. The high PDI explains their naive arrogation of global authority and utterly genuine assumption that everyone ought to just do as they say, simply because they&#8217;re the (self-)designated authority. The research institute setting means that they&#8217;re shut off from the economic real world. Since money is never a big issue, the worship of artificially created fancy titles and institutional authority can become rampant, and it&#8217;s perfectly fine to spend <a target="_blank" href="http://stackoverflow.com/questions/243728/how-to-disable-dtd-at-runtime-in-javas-xpath" >extended amounts of time</a> parsing a 2 page XML document &#8220;the right way&#8221; rather than 15 minutes hacking it and moving on to more pressing problems so your company doesn&#8217;t go bankrupt in the interim.</p>
<p>Moreover, <em>they are still intransigently defending the original poor design choice</em> to use URIs with embedded transport protocols as unique identifiers, because they (as an institution) cannot admit the possibility that this was a poor choice. That would create a great deal of <a target="_blank" href="http://en.wikipedia.org/wiki/Cognitive_dissonance" >cognitive dissonance</a> vis-à-vis their conception of the nature of an institution and its role in dictating what is correct and what is not in the world; their view that institutional authority must be right, because, well, otherwise it wouldn&#8217;t be an institution. After all, <a target="_blank" href="http://en.wikipedia.org/wiki/Argument_from_authority" >everyone there does have more fancy titles</a> than most people who are not there.</p>
<p>These attitudes are pervasive throughout most W3C work, and are the main reason that real-world implementations ignore much of their work.</p>
<h2>Parsing malformed HTML</h2>
<p>So, in any case, I have another problem besides Java trying to load the unavailable DTD. The input HTML is malformed. Not just a little; it&#8217;s utterly broken. It&#8217;s both externally-generated and unreplaceable, so fixing it at the source is not an option. I&#8217;m stuck with it; it&#8217;s the only way to get the data I need. (That&#8217;s real-world programming as opposed to academia right there.)</p>
<h3>Disabling XML validation</h3>
<p>Disabling all XML validation is the obvious solution to both problems, but there is no readily apparent way to do that <code>clojure.xml</code>. Calling <code><a target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html#setValidating%28boolean%29" >setValidating(false)</a></code> on the factory is insufficient. Thanks to <a target="_blank" href="http://stackoverflow.com/questions/243728/how-to-disable-dtd-at-runtime-in-javas-xpath" >Stack Overflow</a>, I found that you must also use<br />
<code><a target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html#setFeature%28java.lang.String,%20boolean%29" >setFeature()</a></code> with several obscure &#8220;<a target="_blank" href="http://www.saxproject.org/apidoc/org/xml/sax/package-summary.html#package_description" >SAX2 Standard Feature Flags</a>&#8220;, as above.</p>
<h3>HTML Tidy to the rescue</h3>
<p>This still leaves the problem of the malformed HTML. There does not seem to be any easy way to make Sax ignore errors. (<code>(.setFeature "http://apache.org/xml/features/continue-after-fatal-error" true)</code> has no apparent effect; it still doesn&#8217;t continue after a fatal parse error.)</p>
<p>In the end, I just ran the malformed input HTML through <a target="_blank" href="http://tidy.sourceforge.net/" >HTML Tidy</a> before attempting to parse it. HTML Tidy coerces the malformed input into valid XML, and Sax is finally happy.</p>
<p>(I now get &#8220;<code>Exception in thread "Swank REPL Thread" java.lang.RuntimeException: java.lang.IllegalMonitorStateException</code>&#8221; from SLIME when I try to actually <em>display</em> the parsed XML in Emacs, but that&#8217;s another matter&#8230;)</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=262&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Randomness with Clojure</title>
		<link>http://www.paullegato.com/blog/randomness-clojure/</link>
		<comments>http://www.paullegato.com/blog/randomness-clojure/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 05:58:49 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[randomness]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=234</guid>
		<description><![CDATA[Psyleron sells a hardware random number generator and software for experimentation on the interaction of consciousness and randomness. As the Psyleron system only runs on Windows, I wrote some quick Clojure to do experimentation with randomness.]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://www.psyleron.com/" >Psyleron</a> sells a hardware random number generator and associated software package for experimentation on the interaction of consciousness and randomness. No, don&#8217;t laugh. <a target="_blank" href="http://www.princeton.edu/~pear/" >Princeton Engineering Anomalies Research</a> conducted decades of methodologically rigorous <a target="_blank" href="http://www.princeton.edu/~pear/human_machine.html"  class="broken_link">research into the nature of randomness</a>. They concluded that deliberate conscious intention can produce a small but statistically significant and reproducible effect on the outcome of stochastic processes. Psyleron is a commercial offshoot of PEAR.</p>
<p>The Psyleron system, unfortunately, costs hundreds of dollars and only runs on Windows, so I wrote some quick Clojure to do experimentation with randomness, using <a target="_blank" href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man4/random.4.html" >/dev/random</a> as the source. (It appears that <a target="_blank" href="http://www.mail-archive.com/cryptography@metzdowd.com/msg00620.html" >/dev/random on Mac OS X does not provide the same quality guarantees</a> as it does on Linux, but it&#8217;s fine for a prototype and the implementation allows easy substitution of another randomness source later.)<span id="more-234"></span></p>
<h2>Clojure random walk generator</h2>
<pre class="brush: clojure; title: ; notranslate">
(ns randomwalker.core
  (:use [incanter core charts]))

(defn random-walk
  &quot;Returns a random walk of length steps. random-fn should return a random integer.&quot;
  [steps list random-fn]
  (if (= 1 steps)
    list
    (recur (dec steps)
           (conj list
                   (+
                    (if (odd? (random-fn)) 1 -1)
                    (or (last list) 0)))
           random-fn)))

(defn dev-random-walk
  &quot;Returns a random walk of length steps based on random numbers read from /dev/random.&quot;
  [steps]
  (with-open [random (java.io.FileInputStream. &quot;/dev/random&quot;)]
    (random-walk steps [0] (fn [] (.read random)))))

(defn view-walk
  &quot;Visualize a random walk.&quot;
  [steps]
  (view (incanter.charts/xy-plot (range 0 (dec steps)) (dev-random-walk steps))))

(defn walk-ratio
  &quot;Generates the given number of random walks and returns the ratio of (walks ending &gt; 0) / (walks ending &lt; 0).&quot;
  [runs steps-per-run greater less]
  (if (zero? runs)
    (double (/ greater less))
    (let [final (last (dev-random-walk steps-per-run))
          ;foo (println final)
          new-greater (if (&gt; final 0) (inc greater) greater)
          new-less (if (&lt; final 0) (inc less) less)]
      (recur (dec runs) steps-per-run new-greater new-less))))
</pre>
<p>This code generates a simple <a target="_blank" href="http://en.wikipedia.org/wiki/Random_walk" >random walk</a>. The user can easily visualize the random walk with <a target="_blank" href="http://incanter.org/" >Incanter</a>, and it looks suspiciously like <a target="_blank" href="http://www.google.com/finance?q=INDEXSP:.INX" >a stock chart</a>.<div id="attachment_236"  class="wp-caption alignright"  style="width: 310px;"><a href="http://www.paullegato.com/wp-content/uploads/2010/04/Clojure-Random-Walker.png"  class="galleryAndCaptionItem" title="Screenshot of the Clojure Random Walker in action"><img src="http://www.paullegato.com/wp-content/uploads/2010/04/Clojure-Random-Walker-300x248.png" alt="Clojure Random Walker screenshot" title="Clojure Random Walker" width="300" height="248" class="size-medium wp-image-236"/></a><span class="wp-caption-text">Screenshot of the Clojure Random Walker in action</span></div></p>
<p>Psyleron type functionality first vaguely appears in <code>walk-ratio</code>. This generates the requested number of random walks and returns the ratio of those that ended above zero to those that ended below. I imagine this will become the basis for some <a target="_blank" href="http://www.psyleron.com/software_reflector.aspx" >Psyleron Reflector</a> style games and experiments.</p>
<p>This is probably not the most efficient way to implement this; any suggestions are welcome. Any ideas for a better source of randomness? Any insight into how the Psyleron games work? Their descriptions are a bit short on the details.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=234&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/randomness-clojure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SQL WHERE clauses in Clojure from S-Expressions</title>
		<link>http://www.paullegato.com/blog/sql-where-clojure-s-expressions/</link>
		<comments>http://www.paullegato.com/blog/sql-where-clojure-s-expressions/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 05:44:48 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[macros]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=208</guid>
		<description><![CDATA[SQL WHERE and HAVING clause strings can be rendered from neat, structured S-expressions with this simple Clojure macro.]]></description>
			<content:encoded><![CDATA[<p>SQL WHERE and HAVING clause strings can be rendered from neat, structured S-expressions with this simple Clojure macro:</p>
<pre class="brush: clojure; title: ; notranslate">
(defmacro sql-expand
  &quot;Transforms nested s-expressions into SQL, for use in WHERE or HAVING clauses.

e.g.: (sql-expand (and (&gt; foo 3)
                       (&lt; bar 4)))

     -&gt; '(foo &gt; 3 AND bar &lt; 4)'

 Nested clauses:

      (sql-expand (or (and (&gt; foo 3) (&lt; bar 4))
                      (&gt; baz 6)))

      -&gt; '((foo &gt; 3 AND bar &lt; 4) OR baz &gt; 6)'

 Embedded arbitrary SQL:
         (sql-expand (and (&gt; foo 3)
                          (&lt; bar \&quot;(SELECT max(foo) + 10 FROM bar)\&quot;)))
      -&gt; '(foo &gt; 3 AND bar &lt; (SELECT max(foo) + 10 FROM bar))'

&quot;
  [form]
  (let [head (first form)]
    (if (includes? '(and or) head)
      `(str &quot;(&quot; (sql-expand ~(second form)) &quot; &quot;
            ~(.toUpperCase (str head)) &quot; &quot;
            (sql-expand ~(last form)) &quot;)&quot;)
      (str (second form) &quot; &quot; head &quot; &quot; (last form)))))
</pre>
<p><span id="more-208"></span></p>
<p>Generating SQL from Lisp has been approached in a few different ways:</p>
<h2>CL-SQL version</h2>
<p><a target="_blank" href="http://clsql.b9.com/manual/ref-syntax.html" >CL-SQL  uses reader macros</a> to do something similar, but with square brackets and new syntax:</p>
<pre class="brush: clojure; title: ; notranslate">
;; From the CL-SQL docs
(sql [select [foo] [bar] :from [baz]] 'having [= [foo id] [bar id]]
     'and [foo val] '&lt; 5)
=&gt; &quot;SELECT FOO,BAR FROM BAZ HAVING (FOO.ID = BAR.ID) AND FOO.VAL &lt; 5&quot;
</pre>
<p>I like my version better as it works with regular S-expressions. No new syntactic constructs are necessary, so you can re-use the parsers already set up in your brain for quick and easy mental code scanning and construction.</p>
<p>Some people mentioned that you have to jump through a lot of hoops to make sure that CL-SQL&#8217;s reader macros are activated and deactivated correctly around your code. Apparently it&#8217;s the only major Common Lisp package that actually uses reader macros extensively. (Clojure doesn&#8217;t support user-provided reader macros anyway, at least not without <a target="_blank" href="http://briancarper.net/blog/clojure-reader-macros" >messy unsupported hackery</a>.)</p>
<h2>Cynojure&#8217;s functional version</h2>
<p><a target="_blank" href="http://cynojure.posterous.com/sql-and-s-expressions-0" >Cynojure has a similar approach</a> to mine:</p>
<pre class="brush: clojure; title: ; notranslate">
;; From Cynojure's blog
 :where (sql-and (sql-= 'role +role-programmer+)
                                 (sql-&lt; 'age 30)))
</pre>
<p>Cynojure <a target="_blank" href="http://github.com/kriyative/cynojure/blob/master/src/cynojure/sql.clj" >uses special <code>sql-*</code> function names</a> instead of transforming an s-expression with a macro. Since <code>and</code> and <code>or</code> are already in use by Clojure itself, he had to use other names. Symbols naming SQL fields (<code>role</code> and <code>age</code>, in this case) must also be quoted. This adds a lot of unnecessary noise to the signal and, as he notes, &#8220;interrupts the flow&#8221; of the code when reading.</p>
<p>By virtue of not automatically evaluating its arguments, a macro-based version can re-use already reserved symbols like <code>and</code> and <code>or</code>, and the user doesn&#8217;t have to bother with messily quoting symbols. This results in much cleaner and more readable code. The user-supplied data for the macro version contain 100% signal and no noise.</p>
<h2>Chouser&#8217;s recursive function within a macro version</h2>
<p><a target="_blank" href="http://groups.google.com/group/clojure/msg/62437f3b96835b58" >Chouser has a different macro-based approach</a> involving a recursive anonymous function:</p>
<pre class="brush: clojure; title: ; notranslate">
;; By Chouser, from http://groups.google.com/group/clojure/msg/62437f3b96835b58
(defmacro where [e]
  (let [f (fn f [e]
            (if-not (list? e)
              [(str e)]
              (let [[p &amp; r] e]
                (if (= p `unquote)
                  r
                  (apply concat (interpose [(str &quot; &quot; p &quot; &quot;)]
                                           (map f r)))))))]
    (list* `str &quot;where &quot; (f e))))
</pre>
<p> His macro allows variable interpolation with quasiquotes, which is really cool. For example, you can do:</p>
<pre class="brush: clojure; title: ; notranslate">
;; Chouser's examples
user=&gt; (where (and (&gt; i (- 3 1)) (&lt; i ~(+ 3 1))))
&quot;where i &gt; 3 - 1 and i &lt; 4&quot;
user=&gt; (let [my-name &quot;'chouser'&quot;] (where (and (&gt; id 0) (= name ~my-name))))
&quot;where id &gt; 0 and name = 'chouser'&quot;
</pre>
<p>This version also avoids the inelegant repetition of the SQL template at lines 25-28 in my version, at the price of slightly more complexity.</p>
<p>The only problem is that it doesn&#8217;t write grouping parentheses in the output SQL string, which discards potentially important grouping information embedded in the s-expression tree and leaves evaluation grouping order to the SQL server:</p>
<pre class="brush: clojure; title: ; notranslate">
(where (or (&lt;= baz 123)
           (and (&gt; foo 3) (&gt; bar 6))))
-&gt; &quot;baz &lt;= 123 or foo &gt; 3 and bar &gt; 6&quot;
</pre>
<h2>My version</h2>
<p>By being aware of the <code>and</code> and <code>or</code> list heads as special case operators which join other clauses together, my version can wrap their output in parentheses, which preserves the evaluation priority implicit within the input S-expression in the final SQL output. It seems that there should be a way to do the same thing both generically and recursively (that is, without repetition of similar code and without conditional recursion), but I can&#8217;t make that work without making the macro significantly longer and more complex (read: fragile), so for the moment, I&#8217;m going to live with simple and slightly repetitious.</p>
<p>One problem lies in knowing when to add parentheses. Although bluntly wrapping the result of every SQL operator and outputting SQL like &#8220;<code>((foo < 3) AND (bar > 4))</code>&#8221; will execute fine on the SQL server, the extra parentheses are superfluous. Ideally, we want to use parentheses only when strictly necessary to preserve the semantic intent of the S-expression tree, not blindly wrap every single expression.</p>
<p>Some sort of awareness of clause-combinatory SQL operators such as AND and OR as special cases is therefore necessary to know when to add parentheses in the output, but I don&#8217;t like having to repeat what&#8217;s essentially the same almost identical output template. In all cases, we have 3 elements, and we&#8217;re just swapping the first two and then taking a string output.</p>
<p>The other issue is that the AND/OR case needs to recurse, but the ordinary case doesn&#8217;t; the ordinary case can be translated directly to a string. The logic would have to be adjusted to either differentiate between these cases and recurse conditionally, or else recurse unconditionally and then have a way to deal with the base case of translating non-trinary lists. That is, with unconditional recursion, a <code>foo</code> symbol will eventually be fed into the macro by itself and must return just the string <code>"foo"</code>, which complicates the management of the SQL string template significantly by forcing you to have multiple templating procedures and then decide between them. (Well, we&#8217;re doing that anyway now, but that would be even worse.)</p>
<p>I messed around with conditionally <code>interpolate</code>ing the template result into a <code>'("(" ")")</code> list, and with conditionally stringifying directly or else building a trinary list based on the structure of the input, but the result was ugly, far longer and far more complicated and confusing than just repeating the template. Any suggestions?</p>
<p>I also haven&#8217;t figured out the best way to add unquote support without making a huge mess. That would be a very cool feature. Any ideas on that are also welcome.</p>
<p>Someday, this macro could be a small part of a user-transparent Clojure object persistence library like <a target="_blank" href="http://common-lisp.net/project/elephant/" >Common Lisp&#8217;s Elephant</a>. That would truly be a killer feature for the Clojure language.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=208&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/sql-where-clojure-s-expressions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Undefining/uninterning a symbol in Clojure</title>
		<link>http://www.paullegato.com/blog/undef-unintern-clojure/</link>
		<comments>http://www.paullegato.com/blog/undef-unintern-clojure/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 05:13:57 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=202</guid>
		<description><![CDATA[How do you undef / unintern a symbol in Clojure? <code>(ns-unmap 'namespace 'symbol)</code>.]]></description>
			<content:encoded><![CDATA[<p>How do you <code>undef</code> / <code>unintern</code> a symbol in Clojure? <code>(ns-unmap 'namespace 'symbol)</code>.<span id="more-202"></span></p>
<p>Suppose that you&#8217;re working at a REPL and you have namespaces a, b, and c, where c <code>:use</code>s both a and b (meaning that it imports their namespace contents into its own namespace.) You write a function <code>foo</code> in a, but then later you decide to move it to b. Bam, you get a namespace collision exception the next time you reload c. </p>
<p>The symbol <code>foo</code> in c&#8217;s namespace is already bound to your code in memory. Simply deleting the source code from a&#8217;s source file is not enough.</p>
<p>Of course, you could be brutish and simply kill your Clojure REPL process and restart it, but who wants to go through all that? We need a way to unbind the obsolete symbol in a. The solution is simple: just</p>
<pre class="brush: clojure; title: ; notranslate">
(ns-unmap 'a 'foo)
</pre>
<p>and the symbol is removed from package a&#8217;s namespace. (This is called <code>undef</code> or <code>unintern</code> in other Lisp dialects.)</p>
<p><em>Edit:</em> Since we&#8217;ve <code>:use</code>d a from c, there will also now be a <code>foo</code> symbol in the c namespace, and we must also <code>(ns-unmap 'c 'foo)</code>. Thanks Meikel!</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=202&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/undef-unintern-clojure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Clojure SQL Dates and Times with Joda</title>
		<link>http://www.paullegato.com/blog/clojure-joda-sql-date-time/</link>
		<comments>http://www.paullegato.com/blog/clojure-joda-sql-date-time/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 04:52:56 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=196</guid>
		<description><![CDATA[The date and time classes built into Java are a horrible mess. What are Clojure programmers to do? Use Joda Time instead. Joda Time is coherently designed and easy to use.
]]></description>
			<content:encoded><![CDATA[<p>The date and time classes built into Java are a horrible mess. What are Clojure programmers to do? Use <a target="_blank" href="http://joda-time.sourceforge.net/" >Joda Time</a> instead. Joda Time is coherently designed and easy to use.</p>
<p>JDBC (at least, the PostgreSQL driver) can&#8217;t use Joda Time directly (without explicit type mapping). One way to convert a Joda LocalDate into something JDBC can use:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn to-sql-date [date]
  &quot;Convert any Joda-readable date object (including a string) to a java.sql.Date&quot;
  (java.sql.Date. (.. (LocalDate. date) toDateMidnight toInstant getMillis)))
</pre>
<p>It&#8217;s not pretty, but it works. You can follow a similar procedure for any of the Joda classes.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=196&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/clojure-joda-sql-date-time/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Setting Clojure&#8217;s Log Level</title>
		<link>http://www.paullegato.com/blog/setting-clojure-log-level/</link>
		<comments>http://www.paullegato.com/blog/setting-clojure-log-level/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 03:35:34 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=177</guid>
		<description><![CDATA[Clojure.contrib.logging doesn't have any way to set the log level. This is obviously a problem if you want to make use of various log levels (debug, warn, etc.) to separate different logging depths. Here's a function to set the logging level.]]></description>
			<content:encoded><![CDATA[<p>Clojure.contrib.logging doesn&#8217;t have any way to set the log level. This is obviously a problem if you want to make use of various log levels (debug, warn, etc.) to separate different logging depths. Here&#8217;s a function to set the logging level on my default clojure.contrib.logging setup:</p>
<pre class="brush: clojure; title: ; notranslate">
;;; This version works when (impl-get-log &quot;&quot;) returns an org.apache.commons.logging.impl.Jdk14Logger
(use 'clojure.contrib.logging)
(defn set-log-level! [level]
  &quot;Sets the root logger's level, and the level of all of its Handlers, to level.
   Level should be one of the constants defined in java.util.logging.Level.&quot;
  (let [logger (.getLogger (impl-get-log &quot;&quot;))]
    (.setLevel logger level)
    (doseq [handler (.getHandlers logger)]
      (. handler setLevel level))))
</pre>
<pre class="brush: clojure; title: ; notranslate">
;;; This version works when (impl-get-log &quot;&quot;) returns a java.util.logging.LogManager$RootLogger
(use 'clojure.contrib.logging)
(defn set-log-level! [level]
  &quot;Sets the root logger's level, and the level of all of its Handlers, to level.
   Level should be one of the constants defined in java.util.logging.Level.&quot;
  (let [logger (impl-get-log &quot;&quot;)]
    (.setLevel logger level)
    (doseq [handler (.getHandlers logger)]
      (. handler setLevel level))))
</pre>
<p>This log level setting function works with a standard out-of-the-box clojure.contrib.logger on my system &mdash;  depending on what logging libraries it finds on your classpath, <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html" >as per the docs</a>, it may not work for you. In particular, you need to be using clojure.contrib.logger to wrap an Apache Commons Logging instance, which in turn wraps a java.util.logging instance. This is the way my system works without any configuration; YMMV. Hopefully, something like this will be assimilated into a universal wrapper in the next clojure.contrib.logging.</p>
<p>For the gory details of how this was constructed&#8230; <span id="more-177"></span></p>
<h2>Changing log levels</h2>
<p>I needed to log some data in my Clojure app. I looked through clojure-contrib and found <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html" >clojure.contrib.logging</a>. It provides a unified logging wrapper for Apache commons-logging, log4j, and java.util.logging.</p>
<p>The <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html#clojure.contrib.logging/spy" ><code>spy</code> macro</a> looks particularly useful for debugging intermediate functions without complicating their code with a bunch of logging cruft: just wrap them in a single tiny <code>spy</code> call, and you&#8217;re set.</p>
<p>Unfortunately, <a target="_blank" href="http://github.com/richhickey/clojure-contrib/blob/655060b3f265026ef3b45b44f5ab22d8897b3034/src/main/clojure/clojure/contrib/logging.clj#L236" ><code>spy</code> logs at the :debug level</a>, and my logger by default seems to be set to <code>:info</code> level. No problem, I thought, I&#8217;ll just increase the log level to <code>:debug</code>&#8230; Hm&#8230; Turns out that there&#8217;s no simple way to do that.</p>
<p><code>clojure.contrib.logging</code> presently includes nothing at all for setting the debug level, in fact, a curious omission of obvious and very basic functionality. So we dig.</p>
<p>Setting the log level must be done in the underlying logging library, since there&#8217;s no clojure.commons.logging wrapper. Looking at <code>*impl-name*</code>, it seems that I&#8217;m using <code>org.apache.commons.logging</code>.</p>
<h3>Apache Commons Logging</h3>
<p>OK, great. Let&#8217;s take a look at the Commons Logging docs. The Commons Logging <a target="_blank" href="http://commons.apache.org/logging/guide.html" >User Guide</a> sounds like a good place to start. Surely changing the log level is a very common task that will be prominently addressed there&#8230; Perhaps even in the <a target="_blank" href="http://commons.apache.org/logging/guide.html#Quick%20Start" >Quick Start guide</a>.</p>
<p>Hmm, nope, nothing about changing the log level, but there <em>is</em> a somewhat disturbing reference to &#8220;a simple <code>commons-logging.properties</code> file&#8221;, conjuring up long-ago memories of Java overengineering and bloat &mdash; an entire configuration file, just to temporarily change the log level?? Surely not&#8230; Also mildly disturbingly, there are references to &#8220;the underlying logging system&#8221;. Commons Logging seems to be, itself, just an abstraction around some other logging system. So I&#8217;m using <em>two</em> layers of logging wrappers now.</p>
<p>Well, let&#8217;s see what Clojure thinks we&#8217;re using:</p>
<pre class="brush: clojure; title: ; notranslate">
&gt; (log/impl-get-log &quot;user&quot;)
#&lt;Jdk14Logger org.apache.commons.logging.impl.Jdk14Logger@13e168&gt;
</pre>
<p>Now we&#8217;re getting somewhere. Let&#8217;s look at <a target="_blank" href="http://commons.apache.org/logging/apidocs/org/apache/commons/logging/impl/Jdk14Logger.html" >Jdk14Logger&#8217;s JavaDocs</a>: the <code>getLogger()</code> &#8211; &#8220;Return the native Logger instance we are using&#8221; method looks promising.</p>
<h3>java.util.logging.Logger</h3>
<pre class="brush: clojure; title: ; notranslate">
&gt; (.. (log/impl-get-log &quot;user&quot;) getLogger)
#&lt;Logger java.util.logging.Logger@1a32f73&gt;
</pre>
<p><code>java.util.logging.Logger</code>! Aha! Let&#8217;s see <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html"  class="broken_link">what we can do with that</a>&#8230; &#8220;The log level &#8230; may also be dynamically changed by calls on the Logger.setLevel method.&#8221; Finally!</p>
<p>This being Java, <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html#setLevel(java.util.logging.Level)" >setLevel() naturally requires an entire object</a> to wrap the integer specifying the log level, with the integer in turn standing in for what we would call a symbol in Lisp (and being referenced symbolically through constants in the Level class.) Ugh. And confusingly, the <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/logging/Level.html#field_summary" >log level constants in that class</a> are named <code>FINE</code>, <code>FINER</code>, <code>FINEST</code>, <code>INFO</code>, <code>OFF</code>, <code>SEVERE</code>, and <code>WARNING</code>, which do not correspond to the :debug, :info, :warn, :error levels used by Clojure and Apache Commons Logging.</p>
<p>Let&#8217;s see what we&#8217;re at now:</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (use 'clojure.contrib.logging)
nil
user&gt; (warn &quot;foo&quot;) ; -&gt; WARNING: foo
nil
user&gt; (info &quot;foo&quot;) ; -&gt; INFO: foo
nil
user&gt; (debug &quot;foo&quot;) ; nothing printed
nil
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getLevel)
nil
;;
;; Nil? WTF?
;;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger )
#&lt;Logger java.util.logging.Logger@197952&gt;
;;
;; Yep, we're using the right object...
;;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getName)
&quot;user&quot;
;;
;; and we have the logger for the correct namespace...
;; it has a getParent() method - maybe it inherits?
;;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getParent)
#&lt;RootLogger java.util.logging.LogManager$RootLogger@1c2df08&gt;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getParent getLevel)
#&lt;Level INFO&gt;
;;
;; AHA. it does.
;;
</pre>
<p>So we&#8217;ve finally tracked down where the log level is set. According to the Javadocs, a logger with a null log level will inherit its parent&#8217;s log level, and changing the parent with <code>setLevel()</code> will also affect any children that are inheriting. The docs tell us that we can get the root logger by asking for the &#8220;&#8221; (empty string) name, so we can simply modify that:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn set-log-level! [level]
&quot;Sets the root logger level.&quot;
  (.setLevel (.getLogger (log/impl-get-log &quot;&quot;)) level))
</pre>
<p>But all is not well:</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (.. (impl-get-log &quot;&quot;) getLogger getLevel)
#&lt;Level FINE&gt;
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
user&gt; (set-log-level! java.util.logging.Level/FINER)
nil
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
user&gt; (set-log-level! java.util.logging.Level/FINEST)
nil
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
user&gt; (set-log-level! java.util.logging.Level/ALL)
nil
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
</pre>
<p>Err&#8230; ok. Maybe that&#8217;s the wrong method? Maybe it&#8217;s not actually setting it?</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (.. (impl-get-log &quot;user&quot;) isDebugEnabled)
true
user&gt; (.. (impl-get-log &quot;&quot;) isDebugEnabled)
true
user&gt; (log :debug &quot;asdf&quot;) ;; prints nothing
nil
user&gt; (debug &quot;asdf&quot;) ;; prints nothing
nil
;;
;; Maybe printing directly to the Java object rather than going through contrib.logger will help?
;;
user&gt; (. (impl-get-log &quot;user&quot;) debug  &quot;foo bar&quot;) ;; prints nothing
nil
user&gt; (. (impl-get-log &quot;&quot;) debug  &quot;foo bar&quot;) ;; prints nothing
nil
user&gt; (. (impl-get-log &quot;user&quot;) warn  &quot;foo bar&quot;) ;; prints &quot;WARNING: foo bar&quot;
nil
</pre>
<p>WTF.</p>
<p>Digging even further into the docs, we find:</p>
<blockquote><p>
 On each logging call the Logger initially performs a cheap check of the request level (e.g. SEVERE or FINE) against the effective log level of the logger. If the request level is lower than the log level, the logging call returns immediately.</p>
<p>After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent&#8217;s Handlers, recursively up the tree.
</p></blockquote>
<p>Great, more Filters of some kind (beyond the log level check filter), a LogRecord object to wrap a string, and an inherited tree of Handlers. All to write a simple level-bound log message to STDERR. (And this is the <em>simple</em> logging library. I shudder to think of log4j&#8217;s internals.)</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (..  (impl-get-log &quot;&quot;) getLogger getFilter)
nil
user&gt; (..  (impl-get-log &quot;user&quot;) getLogger getFilter)
nil
user&gt; (..  (impl-get-log &quot;&quot;) getLogger getHandlers)
#&lt;Handler[] [Ljava.util.logging.Handler;@23f019&gt;
user&gt; (first (..  (impl-get-log &quot;&quot;) getLogger getHandlers))
#&lt;ConsoleHandler java.util.logging.ConsoleHandler@829d91&gt;
user&gt; (.. (first (..  (impl-get-log &quot;&quot;) getLogger getHandlers)) getLevel)
#&lt;Level INFO&gt;
user&gt;
</pre>
<p>So... in the "simple" logger package, we have <strong>two. seperate. levels.</strong> of filtering on the log level, which are entirely uncoordinated. And no mention in the documentation of what exactly these "Filters" and "Handlers" do, or that they can also discard log messages. Certainly no mention at the logger's <code>setLevel()</code> method docs that your setting might be overruled by a "Handler" in some other part of the object tree. (Now, why did I ever stop coding in Java, again...?)</p>
<h3>The working function to set the log level</h3>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (defn set-log-level! [level]
  &quot;Sets the root logger's level, and the level of all of its Handlers, to level.&quot;
  (let [logger (.getLogger (impl-get-log &quot;&quot;))]
    (.setLevel logger level)
    (doseq [handler (.getHandlers logger)]
      (. handler setLevel level))))
#'user/set-log-level!
user&gt; (set-log-level! java.util.logging.Level/ALL)
nil
user&gt; (debug &quot;foo bar&quot;) ;; FINALLY prints &quot;FINE: foo bar&quot;. Not quite what I wanted (&quot;FINE&quot;?), but close enough.
nil
user&gt; (spy (str &quot;abc&quot; &quot;def&quot;)) ;; -&gt; &quot; FINE: (str &quot;abc&quot; &quot;def&quot;) =&gt; abcdef&quot;. cool.
&quot;abcdef&quot;
</pre>
<p>So there you have it. You can now adjust your clojure.contrib.logger log level at runtime &mdash; at least for clojure.contrib.logger wrapping Apache Commons Logging wrapping a java.util.logging logger. No doubt log4j requires its own unique set of black magic. I hope a future version of clojure.contrib.logger will include a universal loglevel-setting function &mdash; I&#8217;ll gladly donate this code to it.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=177&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/setting-clojure-log-level/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

