What is the best design for this class?

suppose this class:

public class Logger
{
    static TextWriter fs = null;

    public Logger(string path)
    {
        fs = File.CreateText(path);
    }

    public static void Log(Exception ex)
    {
        ///do logging
    }

    public static void Log(string text)
    {
        ///do logging
    }
}

and I should use this as:

Logger log = new Logger(path);

and then use Logger.Log()to register what I want. I just use one Logger. The question is, is this a good design? instantiate a class and then always call it a static method? any result of the proposal in the best design is appreciated.

Edit based on Marc answer:

I fill in the last line of the log, and I do not need to read the file while it is open, the problem with the file that is not closed correctly is right. this class just satisfies my requirements and there is no need to be thread safe for it. I just want to read part of the instance, I have to go into SetPath, which you said, any suggestion to close the file?

+3
3

, . SetPath, ( ), . ..

static class, singleton, .

: ! . , , . ; :

private readonly object syncLock = new object();
public static void Log(string value) {
    lock(syncLock) {
        //...
    }
}

( , , - . )

, - , ( , IO), ..; ? , , . .

+3

, . , Logger , TextWriter , . , TextWriter , .

log4net, .

+3

I think you should make the entire static class with a static property that allows you to set the path to the log.

public static class Logger
{
    static TextWriter fs = null;

    public static string FileName
    {
      set
      {
        fs = File.CreateText(value);
      }
    }

    public static void Log(Exception ex)
    {
      if(fs == null) return;
        ///do logging
    }

    public static void Log(string text)
    {
      if(fs == null) return;
        ///do logging
    }
}
0
source

Source: https://habr.com/ru/post/1784359/


All Articles