如何改进此日志类以便可以跨C#多个项目使用它?

时间:2016-07-27 11:06:15

标签: c# logging

我试图确定以下类是否可以在多个C#项目中使用

这个类背后的想法是,如果在程序运行时编辑或删除了一个日志文件,它会自动生成一个日志文件。

public static class Utility {
        #region INTERNAL LOG CLASS
        private static readonly object Lock = new object();

        public static string LogFileName { get; private set; }
        public static string LogFilePath { get; private set; }

        public static string GetDate() => DateTime.Now.ToShortDateString();
        public static string GetTime() => DateTime.Now.ToShortTimeString();

        public static void CreateLog(string filename, string filepath = null) {
            LogFileName = filename;
            var directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
            if (directoryInfo != null)
                LogFilePath = Path.Combine(filepath ?? directoryInfo.FullName, @"files\logs\", LogFileName);

            /* PUT APPROPRIATE WELCOME MESSAGE HERE */
            Log($"# NEW INSTANCE OF '{System.Reflection.Assembly.GetCallingAssembly().GetName().Name}' RUNNING");
            Log($"# LOG CREATED (FILENAME: {LogFileName}, FILEPATH: {LogFilePath})");
        }

        public static void Log(string message, int format = 0) {
            lock (Lock) {
                try
                {
                    string logFormat = $"{GetDate()} @ {GetTime(),-8} |  >";

                    if (format == 0) { message = $"{message}{Environment.NewLine}"; }
                    else if (format == 1) { message = $"{logFormat} ### {message}{Environment.NewLine}"; }
                    else if (format == 2) { message = $"{logFormat} █ERROR█ {message}{Environment.NewLine}"; }
                    else if (format == 3) { message = $"{logFormat} --- {message} --- {Environment.NewLine}"; }
                    else { message = $"{logFormat} {message}{Environment.NewLine}"; }

                    LogToConsole(message);
                    AppendAllText(LogFilePath, message);
                } catch (DirectoryNotFoundException ex) {
                    MessageBox.Show("ERROR"); throw ex; //Count not open / create file.
                }
            }
        }

        public static void LogToConsole(string message) {
            Console.WriteLine(message);
        }

        public static void OpenLog() {
            Process.Start(new ProcessStartInfo { FileName = LogFilePath, UseShellExecute = true });
        }

        public static void ClearLog() {
            WriteAllText(LogFilePath, string.Empty);
            Log("LOG CLEARED!", 1);
        }
        #endregion

您是否有任何问题可以改变/考虑改变?

1 个答案:

答案 0 :(得分:1)

我有一些建议......

我同意donners45尝试在存储日期时尽可能使用UTC,并在需要将其显示给用户时转换为本地时间。

如果你想让它可移植,可能会避免使用MessageBox,因为在某些应用程序中这可能不合适/可用。

也许使用Enum作为格式而不是传递幻数。有点像...

public enum LogFormat
    {
        Message,
        Hash,
        Error,
        Dash
    }

    public static void Log(string message, LogFormat format = LogFormat.Message)
    {
        lock (Lock)
        {
            try
            {
                string logFormat = $"{GetDate()} @ {GetTime(),-8} |  >";

                switch (format)
                {
                    case LogFormat.Message:
                        message = $"{message}{Environment.NewLine}";
                        break;

                    case LogFormat.Hash:
                        message = $"{logFormat} ### {message}{Environment.NewLine}";
                        break;

                    case LogFormat.Error:
                        message = $"{logFormat} ERROR {message}{Environment.NewLine}";
                        break;

                    case LogFormat.Dash:
                        message = $"{logFormat} --- {message} --- {Environment.NewLine}";
                        break;

                    default:
                        message = $"{logFormat} {message}{Environment.NewLine}";
                        break;

                }

                LogToConsole(message);
                File.AppendAllText(LogFilePath, message);
            }
            catch (DirectoryNotFoundException ex)
            {
                LogToConsole($"Error writing log: {ex.Message}");
                throw;
            }
        }
    }

要考虑的其他事情是创建一个记录器界面并在您的应用程序中使用它。您可以编写文件系统实现,但是如果您稍后改变主意,比如说登录数据库,您可以编写新的实现,而不必更改使用它的代码(只需创建实现的任何地方)

例如......

public enum LogFormat
{
    Message,
    Hash,
    Error,
    Dash
}

public interface ILogger
{
    void Log(string message, LogFormat format);

    void LogToConsole(string message);

    void ClearLog();
}


public class FileSystemLogger : ILogger
{
    public void Log(string message, LogFormat format)
    {
        // Your filesystem logging code here...
    }

    public void LogToConsole(string message)
    {
        Console.WriteLine(message);
    }

    public void ClearLog()
    {
        // Your filesystem logging code here...
    }
}

public class DatabaseLogger : ILogger
{
    public void Log(string message, LogFormat format)
    {
        // Your database logging code here...
    }

    public void LogToConsole(string message)
    {
        Console.WriteLine(message);
    }

    public void ClearLog()
    {
        // Your database logging code here...
    }
}