修改WriteLine方法的行为?

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 个重载,因此对于看似简单的事情来说,感觉像是浪费精力。

shi*_*ngo 5

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。

  • 这正确地回答了问题,但我几乎觉得它是不完整的,而不提到替换 Console.Out 首先是问题的错误解决方案。您应该使用日志记录框架,而不是直接写入 Console.Out。然后,可以轻松地将日志记录框架配置为使用自定义格式写入不同的输出,甚至可以处理更复杂的需求,例如每天滚动到新的日志文件,或者当日志文件达到给定大小时。 (2认同)