Simple text logging for a C# console application

Simple logging to text file into a directory called ‘logs’ inside the directory of the executing image.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
private static object objLock = new object();

public static void LogInfo(string d)
{
var sb = new StringBuilder();
sb.AppendFormat("INFO : {0} {1}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), Environment.NewLine);
sb.Append(d);
Log(sb.ToString());
}

public static void LogError(Exception ex)
{
var sb = new StringBuilder();
sb.AppendFormat("EXCEPTION : {0} {1}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), Environment.NewLine);
sb.AppendFormat("{0}{1}", ex.Message, Environment.NewLine);
sb.AppendFormat("{0}{1}", ex.StackTrace, Environment.NewLine);
Log(sb.ToString());
}

static void Log(string d)
{
Console.WriteLine(d);
var _logsDir = "logs";

if (!Directory.Exists(_logsDir))
Directory.CreateDirectory(_logsDir);

lock (objLock)
{
var path = Path.Combine("logs", LogFileName());
using (StreamWriter sw = new StreamWriter(path, true))
{
sw.WriteLine(d);
sw.WriteLine(" ");
sw.Close();
}
}
}

static string LogFileName()
{
return DateTime.Now.ToString("ddMMyyyy") + ".log";
}