locked
custom log file not writing logs RRS feed

  • Question

  • User-73514677 posted

    HI.

    I am trying to create a custom log file and add log information, on the various stages of the application.

    The log file is getting created but no information is getting added to the logs. Below is the code used:

    // Logger class
    
    public static StreamWriter outfileJoblog;
    public  void Init_JobLog(string argLogDir)
            {
                string strDate;            
                
                strDate = DateTime.Today.ToShortDateString().Replace("/", "");
    
                argLoggDir = argLogDir + "Prj1_" + strDate + ".log";
                try
                {
                    outfileJoblog = File.CreateText(argLoggDir);
                    string fullPath = Path.GetFullPath(argLoggDir);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
     public  void Gen_WriteJobLog(string pinstr)
            {            
                outfileJoblog.WriteLine(pinstr);
                outfileJoblog.WriteLine();
            }
    
    // main.cs
    static CustomLogger objLogger = new CustomLogger();
    page_load()
    {
    objLogger.Init_JobLog(filepath);
    
    objLogger.Gen_WriteJobLog("Process started for Country : " + country + ". Run Date : " + System.DateTime.Now);
    objLogger.Gen_WriteJobLog("*******************************************************************");
    }

    How to fix this?

    Thanks

    Monday, November 30, 2020 6:08 PM

All replies

  • User475983607 posted

    Given the state of your code, I recommend using a logging library rather than writing your own,  Just do a Google search.

    Monday, November 30, 2020 7:12 PM
  • User-73514677 posted

    Hi.

    Thanks for the response. There is not an issue in creating the file. I am trying to figure, why the logs are not written. I do not want to use any other logging library for this.

    Tuesday, December 1, 2020 4:04 AM
  • User475983607 posted

    I do not want to use any other logging library for this.

    The code is not thread safe, the stream writer is never disposed, I expect a constructor, and frankly the design is very poor.  It seems like you did not read the SreamWriter documentation and assumed how the SreamWriter works.  Plus it seems like you do not understand C# classes which is odd for someone with your experience on the forum.  That's why I think you should use an existing logger.  There are many and they are easy to use.

    Below is an example that you can update to suite your needs.  I recommend reading the reference documentation.

    public class CustomLogger<T> where T: class
    {
        private readonly string _directory;
        private readonly string _filepath;
        public CustomLogger(string folder)
        {
            _directory = folder;
            _filepath = Path.Combine(_directory, $"{Guid.NewGuid()}.txt");
        }
    
        public void Log(string message)
        {
            if(!Directory.Exists(_directory))
            {
                Directory.CreateDirectory(_directory);
            }
    
            if(!File.Exists(_filepath)) 
            {
                FileStream fs = File.Create(_filepath);
                fs.Close();
            }
    
            using (FileStream fs = File.Open(_filepath, FileMode.Append, FileAccess.Write, FileShare.None))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes($"{typeof(T).Name} {DateTime.Now.ToString()}: {message}\r\n");
                fs.Write(info, 0, info.Length);
            }
        }
    }

    Implementation in Web Forms

    public partial class _default : System.Web.UI.Page
    {
        CustomLogger<_default> logger;
        protected void Page_Load(object sender, EventArgs e)
        {
            string path = Server.MapPath("~/log");
            logger = new CustomLogger<_default>(path);
    
            logger.Log("This is a test");
    
            logger.Log("This is another log test");
        }
    }



     

    Tuesday, December 1, 2020 1:14 PM