Class: Rufio::CommandLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/rufio/command_logger.rb

Overview

コマンド実行ログを保存・管理するクラス

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(log_dir) ⇒ CommandLogger

初期化

Parameters:

  • log_dir (String)

    ログディレクトリのパス



13
14
15
16
# File 'lib/rufio/command_logger.rb', line 13

def initialize(log_dir)
  @log_dir = log_dir
  FileUtils.mkdir_p(@log_dir) unless Dir.exist?(@log_dir)
end

Instance Attribute Details

#log_dirObject (readonly)

Returns the value of attribute log_dir.



9
10
11
# File 'lib/rufio/command_logger.rb', line 9

def log_dir
  @log_dir
end

Instance Method Details

#cleanup_old_logs(max_logs:) ⇒ Object

古いログを削除

Parameters:

  • max_logs (Integer)

    保管する最大ログ数



44
45
46
47
48
49
50
51
52
# File 'lib/rufio/command_logger.rb', line 44

def cleanup_old_logs(max_logs:)
  logs = list_logs
  return if logs.size <= max_logs

  logs_to_delete = logs[max_logs..-1]
  logs_to_delete.each do |log_file|
    File.delete(log_file)
  end
end

#list_logsArray<String>

ログファイル一覧を取得(新しい順)

Returns:

  • (Array<String>)

    ログファイルのパス一覧



38
39
40
# File 'lib/rufio/command_logger.rb', line 38

def list_logs
  Dir.glob(File.join(@log_dir, "*.log")).sort.reverse
end

#log(command, output, success:, error: nil) ⇒ Object

コマンド実行ログを保存

Parameters:

  • command (String)

    実行したコマンド

  • output (String)

    コマンドの出力

  • success (Boolean)

    実行が成功したかどうか

  • error (String, nil) (defaults to: nil)

    エラーメッセージ(失敗時)



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rufio/command_logger.rb', line 23

def log(command, output, success:, error: nil)
  timestamp = Time.now
  filename = generate_filename(command, timestamp)
  filepath = File.join(@log_dir, filename)

  content = format_log_content(command, output, timestamp, success, error)

  # ディレクトリが存在しない場合は作成(バックグラウンドスレッドでの実行時の競合を防ぐ)
  FileUtils.mkdir_p(@log_dir) unless Dir.exist?(@log_dir)

  File.write(filepath, content)
end