C# 라이브러리를 만들자 세번째 강의입니다.
자신의 라이브러리를 구축하는 것은 프로그래머로서 재산을 축적하 것과 같다고 생각합니다.
이전 강의에서 만들었던 LogManager Class를 몇 개의 Option을 이용해서 확장해 보겠습니다.
전체 설명은 아래 YouTube를 참조하시고 코드 부분만 밑에 넣도록 하겠습니다.
BabyCarrot.Tools.LogManager
using System;
using System.IO;
namespace BabyCarrot.Tools
{
public enum LogType { Daily, Monthly }
public class LogManager
{
private string _path;
#region Constructors
public LogManager(string path, LogType logType, string prefix, string postfix)
{
_path = path;
_SetLogPath(logType, prefix, postfix);
}
public LogManager(string prefix, string postfix)
: this(Path.Combine(Application.Root, "Log"), LogType.Daily, prefix, postfix)
{
}
public LogManager()
: this(Path.Combine(Application.Root, "Log"), LogType.Daily, null, null)
{
}
#endregion
#region Methods
private void _SetLogPath(LogType logType, string prefix, string postfix)
{
string path = String.Empty;
string name = String.Empty;
switch (logType)
{
case LogType.Daily:
path = String.Format(@"{0}\{1}\", DateTime.Now.Year, DateTime.Now.ToString("MM"));
name = DateTime.Now.ToString("yyyyMMdd");
break;
case LogType.Monthly:
path = String.Format(@"{0}\", DateTime.Now.Year);
name = DateTime.Now.ToString("yyyyMM");
break;
}
_path = Path.Combine(_path, path);
if (!Directory.Exists(_path))
Directory.CreateDirectory(_path);
if (!String.IsNullOrEmpty(prefix))
name = prefix + name;
if (!String.IsNullOrEmpty(postfix))
name = name + postfix;
name += ".txt";
_path = Path.Combine(_path, name);
}
public void Write(string data)
{
try
{
using (StreamWriter writer = new StreamWriter(_path, true))
{
writer.Write(data);
}
}
catch (Exception ex)
{ }
}
public void WriteLine(string data)
{
try
{
using (StreamWriter writer = new StreamWriter(_path, true))
{
writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss\t") + data);
}
}
catch (Exception ex)
{ }
}
#endregion
}
}
No comments:
Post a Comment