Skip to content

Instantly share code, notes, and snippets.

@kachick
Created May 22, 2012 04:22
Show Gist options
  • Select an option

  • Save kachick/2766539 to your computer and use it in GitHub Desktop.

Select an option

Save kachick/2766539 to your computer and use it in GitHub Desktop.
昔でっちあげたもの - ログファイルへの追記を監視して、増えるの検知するたびにサウンド再生
::
::Description:
:: ログ生成バッチ
::
::Usage:
:: 叩けば動きます。
::
::Lastupdate:
:: 2011/01/20
::
::Author:
:: Kenichi Kamiya
::
::::::::::::::::::::::::::::::::::::::::::::::
@echo off
setlocal
set logfile=logger_%date:~0,4%%date:~5,2%%date:~8,2%.log
echo %date%_%time%: 'logger.bat' Executed >> %logfile%
endlocal
#! ruby -Ks
# -*- coding: shift_jis -*-
#= About
# ログファイルを監視(Windowsでtail -fっぽく)して、行追加毎にサウンドアラートを発生させる。
#
#== Usage
# -引数指定しなければ標準値で動く
# -引数(~4)指定すれば、それに沿って動く
# --引数1 監視間隔
# --引数2 サウンドファイル
# --引数3 監視対象ログ
# --引数4 自身の動作ログ
#== Test
# 1.8.7
#== Author
# Kenichi Kamiya
#== History
#* 0.1.0 2011/01/20 とりあえず動いた。
#* 0.1.1 2011/01/21
# -1行毎アクションを、全差分毎に変更。
# -引数での動作指定に対応
# -表示ログの整形(自分のログと監視ログの区別をつけ易くした)
require 'Win32API'
class IO
SEPARATOR = ('-' * 72).freeze
def logger(*message)
puts SEPARATOR, "#{Time.now.strftime '%Y/%m/%d_%H:%M:%S'}> ", message
flush
end
end
class LogToSoundAlert
Version = '0.1.2'.freeze
def initialize(monitored_log, exec_log, sound_file, interval)
@monitored_log = monitored_log
@exec_log = exec_log
@sound_file = sound_file
@interval = interval
@separator = '-' * 72
@sound_player = Win32API.new('winmm', 'PlaySound', %w(p p l), 'i')
end
def guidance
"#{@interval}秒間隔で'#{@monitored_log}'を監視し、追記検知時に'#{@sound_file}'を再生します。"
end
def usage
puts(
@separator,
'# LogToAlert',
"# Version: #{Version}",
'# LastUpdate: 2011/01/21',
"# #{guidance}",
'# 終了する際は 「ctrl + c」を利用して下さい',
@separator
)
end
def alert
@sound_player.call @sound_file, nil, 0
end
def run
open @exec_log, 'a' do |own|
begin
own.logger guidance
usage
open @monitored_log do |monitored|
own.logger "#{@monitored_log}の監視を開始しました。"
loop do
unless (tail = monitored.read).empty?
formated = tail.gsub(/^/, ' ')
$stdout.logger formated
alert
own.logger(
'OriginalMessage->',
formated,
'<-OriginalMessage',
'MyAction: Play Sound'
)
end
sleep @interval
end
end
rescue Interrupt
message = "中断指示により、#{@monitored_log}の監視を終了しました。"
own.logger message
$stderr.logger message
raise
rescue Exception => ep
message = "予期しないエラーにより、#{@monitored_log}の監視を終了しました。"
own.logger message, ep
$stderr.logger message
raise
end
end
end
end
if $PROGRAM_NAME == __FILE__
today = Time.now.strftime '%Y%m%d'
interval = ARGV[0] || 2
sound_file = ARGV[1] || 'Alarm.wav'
monitored_log = ARGV[2] || "logger_#{today}.log"
own_log = ARGV[3] || "LogToAlert_#{today}.log"
LogToSoundAlert.new(monitored_log, own_log, sound_file, interval).run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment