一、前言 最近在搞C#的winform窗体应用,需要监听Console日志写入本地日志,类似Unity的Application.logMessageReceviedThreaded。 二、具体实现 1、原理 Console提供了一个SetOut接口,传入一个TextWri
一、前言
最近在搞C#的winform窗体应用,需要监听Console日志写入本地日志,类似Unity的Application.logMessageReceviedThreaded。
二、具体实现
1、原理
Console提供了一个SetOut接口,传入一个TextWriter,即可通过TextWriter重写Write和WriteLine接口,将日志写入我们的日志文件了。
public static void SetOut(TextWriter newOut);
2、具体实现
自己创建一个类,比如LoggerTextWriter,它继承TextWriter,重写Write和WriteLine接口,写入日志到本地。
LoggerTextWriter logSW = new LoggerTextWriter("./");
logSW.Init();
Console.SetOut(logSW);
Console.WriteLine("Hello Wrold");
其中LoggerTextWriter代码如下
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class LoggerTextWriter : TextWriter
{
private string m_outputLogPath;
public LoggerTextWriter (string launcherDir) : base()
{
m_outputLogPath = Path.Combine(launcherDir, "output.log");
}
public override Encoding Encoding { get { return Encoding.UTF8; } }
public override void Write(string value)
{
WriteLog(value);
}
public override void WriteLine(string value)
{
WriteLog(value);
}
public override void Close()
{
base.Close();
}
public void Init()
{
if (File.Exists(m_outputLogPath))
{
File.Delete(m_outputLogPath);
}
}
public void WriteLog(string msg)
{
try
{
FileStream fs;
StreamWriter sw;
StringBuilder sbr = new StringBuilder(16);
if (!File.Exists(m_outputLogPath))
{
fs = new FileStream(m_outputLogPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
sw = new StreamWriter(fs, Encoding.UTF8);
sbr.Append("日志开始");
sbr.AppendLine();
}
else
{
fs = new FileStream(m_outputLogPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
sw = new StreamWriter(fs, Encoding.UTF8);
}
sbr.Append("[");
sbr.Append(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff"));
sbr.Append("]: ");
sbr.Append(msg);
sw.WriteLine(sbr.ToString());
sw.Flush();
sw.Close();
fs.Close();
sbr.Clear();
}
catch (Exception)
{
throw;
}
}
}