Files
MusicDownloader/MusicDownloader/Class/LogManager.cs
T
armonica 93403e631b 共通Youtubeフォルダ集約・重複防止・Powerampプレイリスト生成・安全ステージング・ログファイル出力対応
- 全曲を共通フォルダ「Youtube」へ集約し、downloaded_tracks.json による重複防止と再利用に対応
- 同名別動画(Another vocal等)の上書き衝突防止(連番付与)
- Google Drive同期競合を避けるローカル作業フォルダでの完結・一括転送
- Android Poweramp対応プレイリスト(.m3u8)の自動生成
- 429/403エラーに対する多段階フォールバックと失敗時再試行
- Channelを用いた非同期ファイルログ出力(C:\feeds\Log\)の実装
- compose.yaml にログボリュームマウント追加
- .gitignore の整理
2026-09-13 22:27:02 +09:00

154 lines
5.0 KiB
C#

using System;
using System.IO;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace MusicDownloader.Class
{
/// <summary>
/// アプリケーション全体のログ管理クラス
/// コンソールへのカラー出力および C:\feeds\Log\ への非同期ファイル書き込み(MusicDownloader_日付.log)を行う
/// </summary>
public static class LogManager
{
private class LogMessage
{
public string Message { get; set; } = "";
public DateTime Timestamp { get; set; }
}
private static readonly object _consoleLock = new object();
private static readonly Channel<LogMessage> _channel;
private static readonly Task _backgroundTask;
static LogManager()
{
_channel = Channel.CreateUnbounded<LogMessage>(new UnboundedChannelOptions
{
SingleReader = true
});
_backgroundTask = Task.Run(WriteToFileBackgroundAsync);
}
/// <summary>
/// 通常の情報ログを出力
/// </summary>
public static void AddLog(string message)
{
var text = $"[情報] {message}";
WriteToConsole(text, ConsoleColor.Cyan);
EnqueueFileLog(text);
}
/// <summary>
/// 成功ログを出力
/// </summary>
public static void AddSuccess(string message)
{
var text = $"[成功] {message}";
WriteToConsole(text, ConsoleColor.Green);
EnqueueFileLog(text);
}
/// <summary>
/// 警告ログを出力
/// </summary>
public static void AddWarning(string message)
{
var text = $"[警告] {message}";
WriteToConsole(text, ConsoleColor.Yellow);
EnqueueFileLog(text);
}
/// <summary>
/// エラーログを出力
/// </summary>
public static void AddError(string message, Exception? ex = null)
{
var sb = new StringBuilder();
sb.AppendLine($"[エラー] {message}");
if (ex != null)
{
sb.AppendLine($"例外詳細: {ex.Message}");
if (!string.IsNullOrWhiteSpace(ex.StackTrace))
{
sb.AppendLine(ex.StackTrace);
}
}
var fullText = sb.ToString().TrimEnd('\r', '\n');
WriteToConsole(fullText, ConsoleColor.Red);
EnqueueFileLog(fullText);
}
private static void EnqueueFileLog(string text)
{
var log = new LogMessage
{
Message = text,
Timestamp = DateTime.Now
};
_channel.Writer.TryWrite(log);
}
private static void WriteToConsole(string message, ConsoleColor color)
{
lock (_consoleLock)
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Console.ForegroundColor = color;
Console.WriteLine($"[{timestamp}] {message}");
Console.ResetColor();
}
}
/// <summary>
/// バックグラウンドでログファイル(C:\feeds\Log\MusicDownloader_日付.log)に書き込むタスク
/// </summary>
private static async Task WriteToFileBackgroundAsync()
{
await foreach (var log in _channel.Reader.ReadAllAsync())
{
try
{
var logDir = CmnDefine.GetLogDir();
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
// ファイル名: MusicDownloader_yyyy-MM-dd.log
var fileName = $"MusicDownloader_{log.Timestamp:yyyy-MM-dd}.log";
var filePath = Path.Combine(logDir, fileName);
// 複数行の場合は各行にタイムスタンプを付与
var lines = log.Message.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
using var sw = new StreamWriter(filePath, append: true, Encoding.UTF8);
foreach (var line in lines)
{
await sw.WriteLineAsync($"[{log.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] {line}");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"ログファイル書き込みエラー: {ex.Message}");
}
}
}
/// <summary>
/// キューを完了し、溜まっているすべてのログがファイルに書き込まれるまで待機
/// </summary>
public static async Task FlushAndCloseAsync()
{
_channel.Writer.Complete();
if (_backgroundTask != null)
{
await _backgroundTask;
}
}
}
}