Created
June 19, 2022 14:05
-
-
Save kristofzerbe/4f80cb67e5a3d65c0f7d528af493bf5c to your computer and use it in GitHub Desktop.
Simplest Console File Logger (Files)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DoSomething | |
{ | |
public void Work(string p1) | |
{ | |
//... doing heavy work | |
Main.Log("Heavy work done with result", "SUCCESS"); | |
} | |
public void MoreWork(string p2) | |
{ | |
//... doing heavy work | |
Main.Log("More work done with result", "SUCCESS"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Parameter | |
{ | |
public string Param1 = ""; | |
public string Param2 = ""; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
// TOP-LEVEL ARGUMENTS | |
Main.Start(args); | |
// MAIN MODULE | |
static public class Main { | |
static Parameter PARAMETER = new Parameter(); | |
static StringBuilder LOGDATA = new StringBuilder(); | |
static public void Start(string[] args) | |
{ | |
//Process Arguments | |
foreach (string arg in args) | |
{ | |
var a = arg.Split(':'); | |
switch (a[0].ToUpper()) | |
{ | |
case "PARAM1": PARAMETER.Param1 = a[1]; break; | |
case "PARAM2": PARAMETER.Param1 = a[1]; break; | |
default: break; | |
} | |
} | |
DoSomething ds = new DoSomething(); | |
ds.Work(PARAMETER.Param1); | |
ds.MoreWork(PARAMETER.Param2); | |
HandleEnd(); | |
} | |
public static void Log(params string[] args) | |
{ | |
var msg = string.Join(" ", args).TrimEnd(); | |
Console.WriteLine(msg); | |
LOGDATA.AppendLine(msg); | |
} | |
static void HandleEnd() | |
{ | |
if (LOGDATA.Length > 0) | |
{ | |
string logFile = $"{DateTime.Now.ToString("u").Replace(":","-")}.log"; | |
string logFilePath = Path.Combine(Environment.CurrentDirectory, logFile); | |
StreamWriter logStream = new StreamWriter(logFilePath, true, Encoding.UTF8); | |
logStream.Write(LOGDATA); | |
logStream.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment