use*_*376 1 c# console-application static-classes
我需要一个非常简单的想象的东西 - 修改System.Console类方法WriteLine不仅可以写入控制台,还可以写入文本日志文件。
我只需要在调用 WriteLine 之前使用预设参数运行此函数,然后执行通用 WriteLine:
class Logger
{
static public void WriteLog(string logMessage, string fileName ,bool addTimeStamp = true)
{
//Getting temp folder
string destPath = Path.GetTempPath();
//Creating folder
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
//Naming log file
var filePath = String.Format("{0}\\{1}.log",
destPath,
fileName
);
//Writing to timestamp
if (addTimeStamp)
{
logMessage = String.Format("[{0}] - {1}{2}",
DateTime.Now.ToString("HH:mm:ss", CultureInfo.CurrentCulture),
logMessage,
Environment.NewLine);
}
else
{
logMessage = String.Format("{0}{1}",
logMessage,
Environment.NewLine);
}
//Writing to log
File.AppendAllText(filePath, logMessage);
}
}
Run Code Online (Sandbox Code Playgroud)
我考虑过继承,但我什至无法创建一个类,因为“静态类 ConsoleX 无法从 Console 类型派生。静态类必须从对象派生”。
有没有简单的方法来包装 WriteLine 方法?我会为它创建一个单独的(不是继承的)类,但随后我需要为此方法创建 18 个重载,只是为了将参数传递给通用 WriteLine 的 18 个重载,因此对于看似简单的事情来说,感觉像是浪费精力。
Console.WriteLine相当于Console.Out.WriteLine,因此您可以实现自己的TextWriter并将其传递给以Console.SetOut达到您的目的。
顺便说一句,类不能以任何方式继承静态类。
class ConsoleOut : TextWriter
{
private TextWriter _oldOut = Console.Out;
// This overload method is the base method of all
// Write or WriteLine overloads.
// But you can override other methods as you want
public override void Write(char[] buffer, int index, int count)
{
// Write to the original console
_oldOut.Write(buffer, index, count);
// Write to file
Logger.Write(buffer, index, count);
}
}
Console.SetOut(new ConsoleOut());
Run Code Online (Sandbox Code Playgroud)
BTW 2,默认的控制台输出是同步的,但你的方法不是,这是你需要考虑的,因为你可能会得到 IOException。
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |