简体   繁体   中英

Modify the behaviour of WriteLine method?

I need a very simple to imagine thing - modify System.Console class method WriteLine to write not only in console, but also in text log file.

I simply need to run this function with preset arguments prior to any call to WriteLine and then do generic 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);
    }
}

I thought about inheritance, but I cannot even create a class since "Static class ConsoleX cannot derive from type Console. Static classes must derive from object" .

Is there at all simple way to wrap around WriteLine method? I would do a separate (not inherited) class for it but then I need to create like 18 overloads for this method just to pass through arguments to 18 overloads of generic WriteLine, so it feels like waste of effort for seemingly simple thing.

Console.WriteLine is equivalent to Console.Out.WriteLine , so you can implement your own TextWriter and pass it to Console.SetOut to achieve your purpose.

BTW a class can not inherit a static class in any way.

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());

BTW 2, the default console ouput is synchronized, but your method isn't, this is what you need to consider, because you may get IOException.

It is not possible to create a derived class from a static class in C#. A static class is a class that cannot be instantiated and therefore cannot be inherited from. Instead, you can use a regular class or an abstract class as a base for a derived class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM