Skip to content

Instantly share code, notes, and snippets.

@thinkerbot
Created September 27, 2011 21:54
Show Gist options
  • Save thinkerbot/1246359 to your computer and use it in GitHub Desktop.
Save thinkerbot/1246359 to your computer and use it in GitHub Desktop.
syslog usage from ruby

Setup

To test syslog, you have to setup syslog. Setting up syslog is system-specific and potentially quite variable because they frequently run syslogd replacements like rsyslogd (Ubuntu) or syslogd-ng. OSX has it's own internal system logger (the apple system logger) that supports the syslog API, but then adds additional stuff (like the 'syslog' command line application).

The idea is to add syslog configs to write to '/var/log/local2.log' for the local2 facility. In all cases, test with this:

logger -s -p local2.info -t example hello world
grep example /var/log/local2.log

Should print the 'hello world' log. These tests allow an alternate log file and/or facility via the SYSLOG_TEST_LOG_FILE and SYSLOG_TEST_FACILITY environment variables.

OS X

OS X has a fairly standard config, for a fairly standard syslogd (although it does not have the bells of something like the [syslogd on FreeBSD][http://www.freebsd.org/doc/handbook/configtuning-configfiles.html]).

echo 'local2.* /var/log/local2.log' > /etc/syslog.config
sudo launchctl unload  /System/Library/LaunchDaemons/com.apple.syslogd.plist
sudo launchctl load  /System/Library/LaunchDaemons/com.apple.syslogd.plist
#
# Test tasks
#
def current_ruby
`ruby -v`.split[0,2].join('-')
end
desc 'Run the tests'
task :test do
puts "Using #{current_ruby}"
tests = Dir.glob('test/**/*_test.rb')
sh('ruby', '-w', '-e', 'ARGV.dup.each {|test| load test}', *tests)
end
require File.expand_path('../test_helper', __FILE__)
class SyslogTest < Test::Unit::TestCase
include TestHelper
def test_new_content_for_syslog
assert newlines.empty?
system "logger -p local2.info -t example hello world"
assert newlines[0] =~ /example\[\d+\]: hello world/
end
end
require 'test/unit'
module TestHelper
SYSLOG_TEST_FACILITY = ENV['SYSLOG_TEST_FACILITY'] || 'local2'
SYSLOG_TEST_LOG_FILE = ENV['SYSLOG_TEST_LOG_FILE'] || '/var/log/local2.log'
def setup
super
@start_pos = File.stat(SYSLOG_TEST_LOG_FILE).size
end
def newlines
File.open(SYSLOG_TEST_LOG_FILE) do |io|
io.pos = @start_pos
io.readlines
end
end
end
@macek
Copy link

macek commented Jul 11, 2013

How did you get gist to allow you to use / in the filenames?

When I try this, I get an error message:

Files can't be in subdirectories.

I've been wanting to be able to do this for a long time. Any help is appreciated :)

@pjg
Copy link

pjg commented Apr 17, 2017

You cannot write directly to syslogd on MacOS anymore. Not even if you use sudo. This is due to syslog being protected by taskgated, which you cannot easily turn off. I haven't found an easy workaround.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment