<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Ellipsis: Tag syslog</title>
    <link>http://typo.pburkholder.com/articles/tag/syslog?tag=syslog</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>...</description>
    <item>
      <title>Ruby and syslog format string error</title>
      <description>&lt;p&gt;Here&amp;#8217;s a noobie mistake.  A daemon I have running to report on new files being uploaded to a webserver started dying on me when the filenames had a &amp;#8217;%&amp;#8217; in them.&lt;/p&gt;


	&lt;p&gt;I was doing a complete &amp;#8216;Duh!&amp;#8217; coding mistake.  Take this program:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
#!/usr/bin/ruby  -w
require 'syslog'

PROGRAM_NAME="testlog" 
LOG_FACILITY=Syslog::LOG_LOCAL2

$log=Syslog.open(PROGRAM_NAME, Syslog::LOG_PID, LOG_FACILITY)
$log.info("Starting args: " + ARGV.join(" "))

exit
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;If you run it:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;t.rb my message&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;You&amp;#8217;ll get this in the log file:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;Oct 23 08:14:06 raymond testlog[7570]: Starting args: my message &lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;However try this:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
$ .rb my "%message" 

./t.rb:11:in `info': malformed format string - %m (ArgumentError)
        from ./t.rb:11

&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;The problem is that &lt;code&gt;syslog&lt;/code&gt; interprets &amp;#8217;%&amp;#8217; in the message string as a &lt;code&gt;printf&lt;/code&gt; style format character.  That&amp;#8217;s the way of the underlying Unix library, like it or not.  And the code will barf if you try @$log.info(&amp;#8220;Starting args #{variable}&amp;#8221;).  The correct way to code is this:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;$log.info("Starting args: %s",  ARGV.join(" "))&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;and the &amp;#8217;%s&amp;#8217; gets the argument string value substituted in.&lt;/p&gt;


	&lt;p&gt;One could write here about the need to sanitize tainted input, but I won&amp;#8217;t.&lt;/p&gt;</description>
      <pubDate>Tue, 23 Oct 2007 08:09:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:e2d31bb6-3b7b-4a90-9b4e-409c10ac8bee</guid>
      <author>Peter Burkholder</author>
      <link>http://typo.pburkholder.com/articles/2007/10/23/ruby-and-syslog-format-string-error</link>
      <category>Ruby and Rails</category>
      <category>syslog</category>
    </item>
  </channel>
</rss>
