Hallo,
ich habe folgendes Problem ich habe einen FileLogger:
public class FileLogger
{
public FileLogger(string LogPath, string LogStart = null, string LogName = null,bool FileCanExitst = false)
{
LogPath += "/";
if (LogName == null)
{
logPath = new FileInfo(LogPath + "Log_" + DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + ".txt").FullName;
}
else
{
logPath = new FileInfo(LogPath + LogName).FullName;
}
if (File.Exists(logPath))
{
if (!FileCanExitst) { throw new Exception("File allready exists"); }
}
else
{
try
{
StreamWriter sw = new StreamWriter(logPath);
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
if (LogStart != null) { CreateLogStart(LogStart); }
}
public readonly string logPath;
private List<Work> works = new List<Work>();
private bool doWork = false;
private void CreateLogStart(string Start)
{
using (StreamWriter sw = new StreamWriter(logPath))
{
sw.WriteLine(Start + "\n");
sw.Close();
}
}
private async Task<int> DoWorks()
{
doWork = true;
using (StreamWriter sw = new StreamWriter(logPath))
{
while (works.Count != 0)
{
Work work = works[0];
sw.WriteLine(work.time.ToLongTimeString() + ": " + work.type.ToString() + ": " + work.Message.ToString());
if (work.innerException)
{
sw.WriteLine(("InnerException: \"" + work.exception.InnerException.ToString() + "\")\n").PadLeft((work.time.ToLongTimeString() + ": ").Length, ' '));
}
works.Remove(work);
}
sw.Close();
}
doWork = false;
return await Task.FromResult<int>(200);
}
private class Work
{
public Work(string message, Tools.FileLogger.LogType type, DateTime Time)
{
this.type = type;
Message = message ?? throw new ArgumentNullException(nameof(message));
time = Time;
}
public Work(Exception exception, Tools.FileLogger.LogType type, bool innerException,DateTime Time)
{
this.exception = exception ?? throw new ArgumentNullException(nameof(exception));
this.type = type;
this.innerException = innerException;
Message = exception.Message;
time = Time;
}
public readonly Exception exception;
public readonly Tools.FileLogger.LogType type;
public readonly bool innerException;
public readonly string Message;
public readonly DateTime time;
}
public enum LogType
{
Error,
Info,
Warning,
Unknown,
MethodSuccess
}
public void Log(Exception exception, LogType type, bool innerException)
{
works.Add(new Work(exception, type, innerException, DateTime.Now));
if (!doWork) { DoWorks().GetAwaiter(); }
}
public void Log(string Message, LogType type)
{
works.Add(new Work(Message, type, DateTime.Now));
if (!doWork) { DoWorks().GetAwaiter(); }
}
}
und ich habe eine Funktion:
Tools.FileLogger logger = new Tools.FileLogger(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "//Logs//").FullName, null, null, true);
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
try
{
return Task.FromResult(new HelloReply { Directrories = new DirectoryInfo(request.Path).FullName });
}
catch (Exception ex)
{
logger.Log(new Exception("There was a Error by Method " + Tools.GetMethodName() + " more details in \"innerException\".", ex), Tools.FileLogger.LogType.Error, true);
throw ex;
}
}
Und ich möchte wenn die Methode Erfolgreich in den Logger diesen Code rein schreiben aber ich weiß nicht wie ich das machen soll.
logger.Log(Tools.GetMethodName() + " Successful", Tools.FileLogger.LogType.MethodSuccess);
Kann mir hierbei jemand helfen?
LG BierDav
Trifft eine Programmiererin ihre Freundin und die Freundin fragt: "Mit welchen Typen hängst du so in letzter Zeit rum?" Die Programmiererin antwortet: „integers, booleans und strings“
Hi,
ohne auf den Logger einzugehen (da solltest du dich wirklich mal in die gängige Praxis einlesen) bräuchtest du etwa folgendes:
var result = Task.FromResult(new HelloReply { Directrories = new DirectoryInfo(request.Path).FullName });
logger.Log(...);
return result;
LG
Sowas heute selbst zu entwickeln, wenn man nicht muss, ist absolut wahnsinnig.
Die Best Practise aus Architektur- und Communitysicht ist sogenanntes Full Structured Logging.
In .NET mit wenigen Zeilen mit Hilfe des Serilog Projekts für verschiedene Sinks/siehe Serilog, was ein Sink ist) in jede Art von Applikation zu integrieren.
PS: bitte keine Exception-Types missbrauchen.
Wenn eine Datei nicht existiert, dann wirft man eine spezifische Exception wie FileNotFoundException; sollte es für einen Fall keine Framework-Exception geben, dann definiert man eine.
Aber Exception
zu werfen ist ein absoluter Anti-Pattern, weil nicht handlebar.
Ansonsten noch nen einfacher Hinweis zur Code-Gestaltung:
Orientiere Dich an den Microsoft Coding Guidelines 😉
- performance is a feature -
Microsoft MVP - @Website - @AzureStuttgart - github.com/BenjaminAbt - Sustainable Code
Danke!!! 😁
LG BierDav
Trifft eine Programmiererin ihre Freundin und die Freundin fragt: "Mit welchen Typen hängst du so in letzter Zeit rum?" Die Programmiererin antwortet: „integers, booleans und strings“