c# Best Method to create a log file

前端 未结 12 554
甜味超标
甜味超标 2020-12-28 13:37

I\'m writing a tool that\'s going to be check the health of workstations across a network, and will fix according to the issues it finds. I want to create a log file as the

相关标签:
12条回答
  • 2020-12-28 13:53

    I found the SimpleLogger from heiswayi on GitHub good.

    0 讨论(0)
  • 2020-12-28 14:01

    add this config file


    *************************************************************************************
    <!--Configuration for file appender-->
    
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
      </configSections>
      <log4net>
        <appender name="FileAppender" type="log4net.Appender.FileAppender">
          <file value="logfile.txt" />
          <appendToFile value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%d [%t] %-5p [%logger] - %m%n" />
          </layout>
        </appender>
        <root>
          <level value="DEBUG" />
          <appender-ref ref="FileAppender" />
        </root>
      </log4net>
    </configuration>
    
    *************************************************************************************
    
    <!--Configuration for console appender-->
    
    
    <configuration>
    
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,
            log4net" />
      </configSections>
    
      <log4net>
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p [%logger] - %m%n" />
          </layout>
        </appender>
       <root>
          <level value="ALL" />
          <appender-ref ref="ConsoleAppender" />
        </root>
      </log4net>
    </configuration>
    
    0 讨论(0)
  • 2020-12-28 14:05

    I'm using thread safe static class. Main idea is to queue the message on list and then save to log file each period of time, or each counter limit.

    Important: You should force save file ( DirectLog.SaveToFile(); ) when you exit the program. (in case that there are still some items on the list)

    The use is very simple: DirectLog.Log("MyLogMessage", 5);

    This is my code:

    using System;
    using System.IO;
    using System.Collections.Generic;
    
    namespace Mendi
    {
    
        /// <summary>
        /// class used for logging misc information to log file
        /// written by Mendi Barel
        /// </summary>
        static class DirectLog
        {
            readonly static int SAVE_PERIOD = 10 * 1000;// period=10 seconds
            readonly static int SAVE_COUNTER = 1000;// save after 1000 messages
            readonly static int MIN_IMPORTANCE = 0;// log only messages with importance value >=MIN_IMPORTANCE
    
            readonly static string DIR_LOG_FILES = @"z:\MyFolder\";
    
            static string _filename = DIR_LOG_FILES + @"Log." + DateTime.Now.ToString("yyMMdd.HHmm") + @".txt";
    
            readonly static List<string> _list_log = new List<string>();
            readonly static object _locker = new object();
            static int _counter = 0;
            static DateTime _last_save = DateTime.Now;
    
            public static void NewFile()
            {//new file is created because filename changed
                SaveToFile();
                lock (_locker)
                {
    
                    _filename = DIR_LOG_FILES + @"Log." + DateTime.Now.ToString("yyMMdd.HHmm") + @".txt";
                    _counter = 0;
                }
            }
            public static void Log(string LogMessage, int Importance)
            {
                if (Importance < MIN_IMPORTANCE) return;
                lock (_locker)
                {
                    _list_log.Add(String.Format("{0:HH:mm:ss.ffff},{1},{2}", DateTime.Now, LogMessage, Importance));
                    _counter++;
                }
                TimeSpan timeDiff = DateTime.Now - _last_save;
    
                if (_counter > SAVE_COUNTER || timeDiff.TotalMilliseconds > SAVE_PERIOD)
                    SaveToFile();
            }
    
            public static void SaveToFile()
            {
                lock (_locker)
                    if (_list_log.Count == 0)
                    {
                        _last_save = _last_save = DateTime.Now;
                        return;
                    }
                lock (_locker)
                {
                    using (StreamWriter logfile = File.AppendText(_filename))
                    {
    
                        foreach (string s in _list_log) logfile.WriteLine(s);
                        logfile.Flush();
                        logfile.Close();
                    }
    
                    _list_log.Clear();
                    _counter = 0;
                    _last_save = DateTime.Now;
                }
            }
    
    
            public static void ReadLog(string logfile)
            {
                using (StreamReader r = File.OpenText(logfile))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                    r.Close();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-28 14:06

    I would recommend log4net.

    You would need multiple log files. So multiple file appenders. Plus you can create the file appenders dynamically.

    Sample Code:

    using log4net;
    using log4net.Appender;
    using log4net.Layout;
    using log4net.Repository.Hierarchy;
    
    // Set the level for a named logger
    public static void SetLevel(string loggerName, string levelName)
    {
        ILog log = LogManager.GetLogger(loggerName);
        Logger l = (Logger)log.Logger;
    
        l.Level = l.Hierarchy.LevelMap[levelName];
        }
    
    // Add an appender to a logger
    public static void AddAppender(string loggerName, IAppender appender)
    {
        ILog log = LogManager.GetLogger(loggerName);
        Logger l = (Logger)log.Logger;
    
        l.AddAppender(appender);
    }
    
    // Create a new file appender
    public static IAppender CreateFileAppender(string name, string fileName)
    {
        FileAppender appender = new
            FileAppender();
        appender.Name = name;
        appender.File = fileName;
        appender.AppendToFile = true;
    
        PatternLayout layout = new PatternLayout();
        layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
        layout.ActivateOptions();
    
        appender.Layout = layout;
        appender.ActivateOptions();
    
        return appender;
    }
    
    // In order to set the level for a logger and add an appender reference you
    // can then use the following calls:
    SetLevel("Log4net.MainForm", "ALL");
    AddAppender("Log4net.MainForm", CreateFileAppender("appenderName", "fileName.log"));
    
    // repeat as desired
    

    Sources/Good links:

    Log4Net: Programmatically specify multiple loggers (with multiple file appenders)

    Adding appenders programmatically

    How to configure log4net programmatically from scratch (no config)

    Plus the log4net also allows to write into event log as well. Everything is configuration based, and the configuration can be loaded dynamically from xml at runtime as well.

    Edit 2:

    One way to switch log files on the fly: Log4Net configuration file supports environment variables:

    Environment.SetEnvironmentVariable("log4netFileName", "MyApp.log");
    

    and in the log4net config:

    <param name="File" value="${log4netFileName}".log/>
    
    0 讨论(0)
  • 2020-12-28 14:06

    You can also take a look at the built-in .NET tracing facilities too. There's a set of trace listeners that allow you to output to a log file, but you can configure it to log into the Event viewer, or to a database (or all of them simultaneously).

    http://www.codeguru.com/csharp/.net/net_debugging/tracing/article.php/c5919/NET-Tracing-Tutorial.htm

    0 讨论(0)
  • 2020-12-28 14:08

    We did a lot of research into logging, and decided that NLog was the best one to use.

    See http://nlog-project.org/

    Also see log4net vs. Nlog and http://www.dotnetlogging.com/comparison/

    0 讨论(0)
提交回复
热议问题