Skip to content

Instantly share code, notes, and snippets.

@kalharbi
Created July 11, 2014 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalharbi/fec7e70cd14e42c31a8e to your computer and use it in GitHub Desktop.
Save kalharbi/fec7e70cd14e42c31a8e to your computer and use it in GitHub Desktop.
Ruby Logging - different channels for different levels. Log errors to FILE and all levels to STDOUT.
require 'logging' # gem install logging
require 'singleton'
class Log
include Singleton
attr_accessor :log_file_name
@@file_name = nil
# set log file name
def self.log_file_name=log_file_name
@@file_name = log_file_name
end
def initialize
# set log file name.
if @@file_name.nil?
@log_file_name = $PROGRAM_NAME + '-' + Time.new.strftime("%Y-%m-%d") + ".log"
else
@log_file_name = @@file_name
end
# only show "info" or higher messages on STDOUT using the Basic layout
Logging.appenders.stdout(:level => :info)
# send all error log events to log file as JSON
begin
Logging.appenders.rolling_file(
@log_file_name,
:level => :error,
:age => 'daily',
:layout => Logging.layouts.json
)
rescue ArgumentError => e
abort(e.message)
end
@logger ||= Logging.logger['my_logger']
@logger.level = :info
@logger.add_appenders @log_file_name, 'stdout'
end
def error(msg)
@logger.error(msg)
end
def warn(msg)
@logger.warn(msg)
end
def info(msg)
@logger.info(msg)
end
def debug(msg)
@logger.debug(msg)
end
end
#!/usr/bin/ruby
require_relative 'log'
class Usage
Log.log_file_name = '/Users/Khalid/error_logs_go_here.log'
@@log = Log.instance
def test
@@log.error("this error message will get logged to both stdout and file.")
@@log.info("this info message will only get logged to stdout.")
@@log.warn("this warning message will only get logged to stdout.")
end
end
if __FILE__ == $PROGRAM_NAME
usage = Usage.new
usage.test
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment