Generate Log by day date C#

Asked

Viewed 116 times

0

I have this code below, would be able to generate Log by date of day? Example: log_29072020.txt

private void Log(string mensagem)
{   
    string ficheiro = Environment
        .GetFolderPath(Environment.SpecialFolder.MyComputer) 
            + @"\Debug\Log.txt";
   
    if (!Directory.Exists(Path.GetDirectoryName(ficheiro)))
        Directory.CreateDirectory(Path.GetDirectoryName(ficheiro));

    StreamWriter file = new StreamWriter(ficheiro, true, Encoding.Default);
    file.WriteLine(DateTime.Now + " > " + mensagem);
    file.Dispose();
}

And create an action of what was made of the system, I just got the message.

2 answers

0

You can format the output with Datetime.Now.ToString("dd mm yy") or something like that. If you want to take a look at the documentation of a loger like log4net, here you can find examples of how to do what you want using this tool. Plus you avoid having to implement file access and you can print logs for multiple outputs.

0


Basically in the file name put as follows:

@"\Debug\log" + DateTime.Now.ToString("ddMMyyyy") + ".txt"

the formatting specified in your question. Final example:

private void Log(string mensagem)
{   
    string ficheiro = Environment
        .GetFolderPath(Environment.SpecialFolder.MyComputer) 
            + @"\Debug\log_" + DateTime.Now.ToString("ddMMyyyy") + ".txt";
   
    if (!Directory.Exists(Path.GetDirectoryName(ficheiro)))
        Directory.CreateDirectory(Path.GetDirectoryName(ficheiro));

    StreamWriter file = new StreamWriter(ficheiro, true, Encoding.Default);
    file.WriteLine(DateTime.Now + " > " + mensagem);
    file.Dispose();
}

I’m paying attention to the file name, not if the code is the best way to solve the problem.

  • Thank you Virgilio Novic

  • if this is the expected response, please tick @Evanilsonsilva

  • in that same code would have to restrict the amount of log created, example: when it arrived in an amount of 30 logs, in the next log it would delete or overwrite the first log, thus always staying the amount of 30 logs, would have to do ?

  • @Evanilsonsilva yes, programming is unlimited, only that there is already another doubt, every doubt generates a question here in pt.stackoverflow for better organization ... so create another question

  • Yeah, thanks again @Virgilio Novic

Browser other questions tagged

You are not signed in. Login or sign up in order to post.