본문 바로가기

Software/C# (.NET Framework)

C# 일자별 텍스트 파일 로그 소스

반응형

일자별로 테스트 파일로 로그를 남기는 기능을 구현하기 위한 방법은

1.     자신이 구현 하는 방법

2.     구현된 소스를 이용하는 방법

보통(?)의 분들을 2번을 선호(?) 하시게 되는데.....  검색을 하다보면

log4net 과 같이 완성형의 로그 기능을 하는 소스도 있습니다.

헌데 쉽게 적용 하기가 껄끄럽습니다. 사용방법도 익혀야 되고....

---------------------------------------------------------------------------------

쉽게 적용 가능한 간단한 소스를 공개 합니다기능을 간단히 나열하면

1.  일별로 텍스트를 나누어서 저장 합니다.

, 1개의 기능을 하고 있습니다.

RollOverLogText.cs


namespace Module_HDEL_DEois.Etc.Log
{
    using System;
    using System.Diagnostics;
    using System.IO;

    /// 
    /// RollOver LogText
    /// 
    public class RollOverLogText : TraceListener
    {
        #region Constants and Fields

        /// 
        /// 파일 이름
        /// 
        private readonly string stringFileName;

        /// 
        /// 현재 시간
        /// 
        private DateTime datetimeNow;

        /// 
        /// 스트림 쓰기용 버퍼버
        /// 
        private StreamWriter streamwriterTrace;

        #endregion

        #region Constructors and Destructors

        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// 
        /// The string file name.
        /// 
        public RollOverLogText(string stringFileName)
        {
            // Pass in the path of the logfile (ie. C:\Logs\MyAppLog.log)
            // The logfile will actually be created with a yyyymmdd format appended to the filename
            this.stringFileName = stringFileName;
            this.streamwriterTrace = new StreamWriter(this.GenerateFilename(), true)
                {
                    AutoFlush = true
                };
        }

        #endregion

        #region Public Methods

        /// 
        /// 쓰기 관련
        /// 
        /// 
        /// The message.
        /// 
        public override void Write(string message)
        {
            // VERSION revision 1 update 1 2011-03-28
            this.CheckRollover();
            if (this.streamwriterTrace.BaseStream.CanWrite)
            {
                this.streamwriterTrace.Write(message);
            }
        }

        /// 
        /// 쓰기 관련 라인
        /// 
        /// 
        /// The message.
        /// 
        public override void WriteLine(string message)
        {
            // VERSION revision 1 update 1 2011-03-28
            this.CheckRollover();
            if (this.streamwriterTrace.BaseStream.CanWrite)
            {
                this.streamwriterTrace.WriteLine(DateTime.Now + " : " + DateTime.Now.Millisecond + " - " + message);
            }
        }

        #endregion

        #region Methods

        /// 
        /// 오버라이드된 소멸자
        /// 
        /// 
        /// The disposing.
        /// 
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.streamwriterTrace.Close();
            }
        }

        /// 
        /// 날짜를 체크
        /// 
        private void CheckRollover()
        {
            // If the date has changed, close the current stream and create a new file for today's date
            if (this.datetimeNow.CompareTo(DateTime.Today) != 0)
            {
                this.streamwriterTrace.Close();
                this.streamwriterTrace = new StreamWriter(this.GenerateFilename(), true)
                    {
                        AutoFlush = true
                    };
            }
        }

        /// 
        /// 파일이름 만들기
        /// 
        /// 
        /// 스트링으로 된 파일 이름
        /// 
        private string GenerateFilename()
        {
            this.datetimeNow = DateTime.Today;

            string stringPath =
                Path.Combine(
                    Path.GetFileNameWithoutExtension(this.stringFileName) + "_" +
                    this.datetimeNow.ToString("yyyy-MM-dd") + Path.GetExtension(this.stringFileName) + ".txt");

            return stringPath;
        }

        #endregion
    }
}


사용방법 선언

// Log_Matrix_2012-03-02.txt 파일을 생성 ( 2012-03-02 는 'yyyy-MM-dd' 형식)
private readonly RollOverLogText logtextWriterMatrix = new RollOverLogText("Log_Matrix");


호출 방법


var stringWriter = string.format("쓰고자 하는 내용");
this.logtextWriterMatrix.WriteLine(stringWriter);
반응형