TEXT 파일로 로그 남기기 :: C#
콘솔로 작성된 C# 프로젝트에서 파일로 관련 로그를 남기는 방법
/// ms까지 시간을 구하는 함수
public string GetDateTime()
{
DateTime NowDate = DateTime.Now;
return NowDate.ToString("yyyy-MM-dd HH:mm:ss") + ":" + NowDate.Millisecond.ToString("000");
}
/// 로그내용
public void Log(String msg)
{
string FilePath = Directory.GetCurrentDirectory() + @"\Logs\" + DateTime.Today.ToString("yyyyMMdd") + ".log";
string DirPath = Directory.GetCurrentDirectory() + @"\Logs";
string temp;
DirectoryInfo di = new DirectoryInfo(DirPath);
FileInfo fi = new FileInfo(FilePath);
try
{
if (di.Exists != true) Directory.CreateDirectory(DirPath);
if (fi.Exists != true)
{
using (StreamWriter sw = new StreamWriter(FilePath))
{
temp = string.Format("[{0}] {1}", GetDateTime(), msg);
sw.WriteLine(temp);
sw.Close();
}
}
else
{
using (StreamWriter sw = File.AppendText(FilePath))
{
temp = string.Format("[{0}] {2} - {1}", GetDateTime(), this.TargetKey, msg);
sw.WriteLine(temp);
sw.Close();
}
}
}
catch (Exception e)
{
}
}