C# Export Logs to 2 txt files

0

So I have a button made from my xaml file (view), called Export. When the user clicks on it, the logs created during the run of the app get exported to Logs.txt. If there are Warnings, Errors or Exceptions, those will instead be created in another txt file called ErrorLogs.txt

Here is my code now:

private bool IsErrorLog(string logText)
{
    
    return logText.Contains(LogType.Error.ToString()) || logText.Contains(LogType.Warning.ToString()) || logText.Contains(Exception);

}

private void btn_ExportLogs_Click(object sender, RoutedEventArgs e)
{
    string logsFolder = "LogsFolder"; // Folder for logs
    if (!Directory.Exists(logsFolder))
    {
        Directory.CreateDirectory(logsFolder);
    }


    string timestamp = DateTime.Now.ToString("hhmmss");
    string logFileName = Path.Combine(logsFolder, $"Logs_{timestamp}.txt");
    string errorLogFileName = Path.Combine(logsFolder, $"ErrorLog_{timestamp}.txt");



    using (StreamWriter logWriter = new StreamWriter(logFileName))
    
    {

        foreach (var item in LogGrid.Children)
        {

            logFileName = $"{item}";
            logWriter.WriteLine(logFileName);

            if (IsErrorLog(logFileName))
            {
                using (StreamWriter errorLogWriter = new StreamWriter(errorLogFileName))
                errorLogWriter.WriteLine(errorLogFileName);
            }
        }

    }
}

My issue here firstly is that I dont know how to add Exception in the isError method return. It says ““Exception” is a type, which is not valid in the given context”

I tried to make a second parameter Exception ex but then I will need to use that second parameter in the if in the btn_ExportLogs_Click method and I dont know what I should put there.

My second issue is that even with this code, all the logs go only in the Logs file, even if I try to make some errors in the app (like deleting something that doesnt exist anymore for example), it will anyways put it in the Logs file like all the other logs, and not create an ErrorLogs.txt and put it there.

I tried putting the using inside the if, and it never creates cause all the logs are in Logs, and when i put the using just under the other using, it was always creating the txt file but always empty.

I tried to make a second parameter Exception ex but then I will need to use that second parameter in the if in the btn_ExportLogs_Click method and I dont know what I should put there.

I tried putting the “using” (errorLogWritter) inside the if, and it never creates the error file cause all the logs are in Logs.txt, and when i put the “using” just under the other “using” (logWritter), it was always creating the txt file but always empty due to the same reason.

In summary I expect that when I do random actions on the app, the logs that get created in the front page to be exported to a Logs.txt when i click on the export button (which means calling the method) but if there are LogType.Warning or/and LogType.Error or/and Exceptions to put them in a separate txt file called ErrorLogs.txt

I have other classes, but also a main classes where with each action it Logs a message, where at the end I say what is the LogType. I am expecting what I wrote to catch on that and differentiate between LogType.Info which is just normal, and the Warning & Error.

I hope i was clear, I am sorry if i’m not.

I tried reading tons of forums and documentations but I couldnt find something that helped me.

Ok, I can see what you are trying to do, but I believe you are overcomplicating it. Most of the time, errors are put first in a text file, then less important logs, (eg. warnings, info, etc). So you could, for example dump the errors in the file first, then the warnings and info like so:

---ERRORS---
Fatal Error: <error name, line, etc>
...
---WARNINGS---
Warning: <warning, line, etc>
...
---INFO---
Info: <Info, timestamp, etc>

I believe this would not require more data to have to be sorted through and processed, saving resources and time.

But, I’ll try answer your question, and hopefully fix your errors.

I’m not able to find the LogGrid class, is it custom?

From what I can see, you are simply doing the equivalent of:

logFileName = item.ToString();

However, I am missing a lot of stuff I would need to help you debug. For example, What is LogType? Do you have a definition for it? Furthermore, do you have a definition of LogGrid?

I wish I am able to help, but I need more information before I could help effectively.

Sorry, Gammer0909

1 Like

Another question is, just to clarify, what c# version are you using: .NET Core or .NET Framework? And what version? That will also affect what’s available and how to access it.

1 Like

You’d better provide a repo that can reproduce your issue so people can test your code locally.

Your code may have potential bugs. The logFileName seems to be the name of the file you want to export. But you reassign it in the foreach statement. I think it’s wrong? Not sure why you reassign it. I think it should be:

        foreach (var item in LogGrid.Children)
        {
            // What type is item here? Make sure to use a string. If your LogGrid is a UI element, the Children might not be a string. You need to convert it to a string, e.g.
            var logText = item. Content; // I don't know if it works.
            logWriter.WriteLine(logText );
           // Omitted

Also, the logic is not very clean because you have nested using statement. You can first filter the logs for normal logs, write to the file, then filter the logs for exception, then write to the error log file. That would avoid nested using.

The IsErrorLog method also has a bug. logText.Contains should use a string as the parameter. You can use logText.Contains("Exception") instead.