프로그램 분석이 훨씬 편해짐.
로그매니저 파일 생성

logManager 코드
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace MakeLibrary.Tools
{
public class LogManager
{
private string _path;
// region은 가독성을 위함.
// 열고 닫을수 있음.
#region Constructors
public LogManager(string path)
{
_path = path;
_SetLogPath();
}
// 두번째 생성자가 첫번째 생성자를 이용함.
// 경로가 들어오지 않는 생성자에서 경로가 들어온 생성자를 호출함.
public LogManager()
: this(Path.Combine(Application.Root, "Log")) // 같은 클래스의 생성자를 의미함.
{
// _path = MakeLibrary.Tools.Application.Root;
// _path = Application.Root;// 같은 폴더라 자동 참조됨.
// 중복이라 this로 첫번째 생성자를 이용함.
//_path = Path.Combine(Application.Root, "Log");
//_SetLogPath();
}
#endregion
#region Methods
private void _SetLogPath()
{
// 파일이 존재 하는지 체크
if (!Directory.Exists(_path))
// 없으면 만들음
Directory.CreateDirectory(_path);
// 파일명은 오늘 날짜명 ,, text파일
string logFile = DateTime.Now.ToString("yyyyMMdd") + ".txt";
// 맴버변수에 저장
_path = Path.Combine(_path, logFile);
}
public void Write(string data)
{
// 만약의 에러를 위함
try
{
// using 선언
// 파일을 알아서 사용하고 닫아줌.
// resouce 관리가 편리함.
// StreamWriter
// 경로에 파일이 없으면 생성시킴. 있으면 추가모드로 열수 있음.
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
}
}
| cs |
test 코드
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
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MakeLibrary.Tools;
namespace TestLibrary2
{
class Program
{
static void Main(string[] args)
{
LogManager log = new LogManager();
log.WriteLine("[Begin Processing]-----");
for( int index=0; index<10; index++)
{
log.WriteLine("Processing: " + index);
// Do 실제 프로그램이 돌음
System.Threading.Thread.Sleep(500);
log.WriteLine("Done: " + index);
}
log.WriteLine("[End Processing]-----");
}
}
}
| cs |
결과
파일 생성후 txt 파일에 로그가 찍힘을 확인할 수 있다.
강좌 : https://www.youtube.com/watch?time_continue=982&v=vbVaBg3wPj4
댓글
댓글 쓰기