I have a problem with app.config
in C#.
I wrote an app.config
with key
and value=DEBUG
, while in main
I wrote
DEBUG,INFO,WARN AND ERROR.
The problem is that the value doesn't work and it's printing the main
into my log without considering the level.
This is my app config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="FolderName" value="C:\Users\mpilas\Desktop\logs\" />
<add key="FileSize" venter code herealue="10240" />
<add key="LogNameType" value="Date"/> <!--Value can be Size or "Date" -->
<add key="Level" value='DEBUG'/>
</appSettings>
</configuration>
My main
is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
namespace ConsoleApplication8 {
class Program {
static void Main(string[] args) {
for (int i = 0; i < 2; i++) {
LogWriter.Write("Hello", Severity.DEBUG);
LogWriter.Write("Hello", Severity.INFO);
LogWriter.Write("Hello", Severity.WARNING);
LogWriter.Write("Hello", Severity.ERROR);
}
}
}
}
and I have one more class with the name :LogWriter
.
namespace ConsoleApplication8 {
public enum Severity { ERROR, WARNING, INFO, DEBUG };
public class LogWriter {
private static string _folder = ConfigurationManager.AppSettings["FolderName"];
private static long _fileSize = int32.Parse(ConfigurationManager.AppSettings["FileSize"]);
private static string kindOfType = ConfigurationManager.AppSettings["LogNameType"];
static LogWriter() {}
private static string GetFileNameByDate() {
string dateName= DateTime.Now.ToString("yyyy-MM-dd");
return _folder + dateName + ".log";
}
private static string GetFileNameBySize() {
string name = "";
int counter = 0;
do {
if (counter == 0) { name = _folder + kindOfType + ".log"; }
else {name = _folder + kindOfType + "-" + counter + ".log"; }
if (File.Exists(name) {
counter++;
FileInfo realFile = new FileInfo(name);
if (realFile.Length > _fileSize) {
name = _folder + kindOfType + "-" + counter + ".log";
}
else { break; }
}
else { break; }
} while (true);
return name;
}
private static string GetFileName() {
clearFiles();
if(kindOfType == "Size") { return GetFileNameBySize(); }
else {
if(kindOfType == "Date") { return GetFileNameByDate(); }
}
return "";
}
public static void Write(string messgae, Severity severity) {
try {
string file = GetFileName();
StreamWriter log = new StreamWriter(file, true);
log.WriteLine(DateTime.Now.ToString() + " " + severity.ToString() + ": [" + messgae + "]");
log.Flush();
log.Close();
}
catch (Exception) {}
}
private static void clearFiles() {
string[] files = Directory.GetFiles(_folder);
foreach (string file in files) {
FileInfo fi = new FileInfo(file);
if (fi.LastAccessTime < DateTime.Now.AddDays(-14)) { fi.Delete(); }
}
}
}
}
How should I treat the key=level
and its value on my application?