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.

4
  • Do you want to check if your log string contains "exception" in it? string.Contains method accepts string as a parameter, so you need to search for "Exception" substring, not just Exception class. This should work: logText.Contains("Exception")
    – Slepoyi
    Commented Nov 24, 2023 at 6:35
  • Wdym contains "exception" in it? Like in my Log Messages in the main class? if i change to logText.Contains("Exception") wouldn't that just try to find the string "Exception" instead of an actual throw Exception? Sorry for all the questions.
    – PinkGoat_
    Commented Nov 24, 2023 at 6:39
  • Yes, it would. But your method IsErrorLog is just a check if logText contains Error, Warning or Exception text (ok, now it actually isn't, but it looks like it is designed to do so). Next, note that you use Error.ToString() and Warning.ToString() (ToString conversion is the only way to check if log string contains smth as a substring). So I decided that you just want to check if your log string contains "Exception" text.
    – Slepoyi
    Commented Nov 24, 2023 at 6:59
  • Ohhhh no I didnt mean to make it search them as just text. I meant when there a log message with LogType.Warning for example, then that log message goes into the ErrorLog.txt instead.
    – PinkGoat_
    Commented Nov 24, 2023 at 7:14

1 Answer 1

0

Wanted to make a comment but there's a lot of text. When I looked more attentively, your code doesn't make much sense to me.

I guess that your item is a string which contains your log message. Then why do you assign logFileName = $"{item}"? That's just unneccessary. You can write item directly to your log.

Next, the line

errorLogWriter.WriteLine(errorLogFileName);

Your errorLogFileName is a path to the error log file. So this code will just write file path into that file, not the error message.

Also, note that if your IsErrorLog check returns true, your log string (in current logic) should be written twice: once in simple log and once in error log (as I understood you don't want such a behavior).

Btw, you want to check if your log string contains warnings, errors, exceptions. The best way to do it is to have a marker which point either your log is warning, error or exception. Some loggers write log level as 3 letters; for example, that's the information log string (the marker is INF):

[10:39:35 INF] Executed endpoint ...

So, considering all the above, and assuming that your log string contains some markers so you can determine its log level, i'd rewrite your code to smth like that:

private bool IsErrorLog(string logText)
{
    
    return IsErrorLog(logTest) || IsWarningLog(logText) || IsExceptionLog(logText);
}

private bool IsErrorLog(string logText)
{
    return logText.Contains("ERR"); // change it for your needs
}

private bool IsWarningLog(string logText)
{
    return logText.Contains("WRN"); // change it for your needs
}

private bool IsExceptionLog(string logText)
{
    return logText.Contains("EXC"); // change it for your needs
}

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))  
    {
        using (StreamWriter errorLogWriter = new StreamWriter(errorLogFileName))
        {
            foreach (var item in LogGrid.Children)
            {
                if (IsErrorLog(logFileName))
                {
                    errorLogWriter.WriteLine(item);
                    continue;
                }

                logWriter.WriteLine(logFileName);
            }
        }
    }
}

The above code creates 2 stream writers (so the won't be re-initialized inside foreach loop). Then, it checks if your item should be written to error or simple log. If it should be written to error log, it is written to it and the cycle continues. Else, log text is written to simple log file.

Hope this was clear.

Not the answer you're looking for? Browse other questions tagged or ask your own question.