IT story

타사 라이브러리를 사용하지 않고 C #으로 로그인하려면 어떻게해야합니까?

hot-time 2020. 9. 5. 10:35
반응형

타사 라이브러리를 사용하지 않고 C #으로 로그인하려면 어떻게해야합니까? [닫은]


내 응용 프로그램에서 로깅을 구현하고 싶지만 log4net과 같은 외부 프레임 워크를 사용하지 않습니다.

그래서 파일에 DOS의 에코 와 같은 작업을하고 싶습니다 . 가장 효과적인 방법은 무엇입니까?

외부 프레임 워크를 사용하지 않고 기록 된 처리되지 않은 예외를 기록하는 방법이 있습니까?


public void Logger(String lines)
{

 // Write the string to a file.append mode is enabled so that the log
 // lines get appended to  test.txt than wiping content and writing the log

  System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt",true);
  file.WriteLine(lines);

  file.Close();

}

자세한 내용은 MSDN :


나는 log4j.net과 같은 외부 프레임 워크를 사용하지 않을 것입니다.

왜? Log4net은 아마도 대부분의 요구 사항을 해결할 것입니다. 예를 들어이 클래스를 확인하십시오 : RollingFileAppender .

Log4net은 잘 문서화되어 있으며 웹에는 수천 개의 리소스와 사용 사례가 있습니다.


이벤트 로그에 직접 쓸 수 있습니다. 다음 링크를 확인하십시오.
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx

다음은 MSDN의 샘플입니다.

using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.");

    }
}

정말 간단한 기록 방법을 찾고 있다면이 라이너를 사용할 수 있습니다. 파일이 없으면 생성됩니다.

System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");

ELMAH를 발견 할 때까지 내 자신의 오류 로깅을 작성했습니다 . ELMAH만큼 완벽하게 이메일 부분을 확인할 수 없었습니다.


If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.


If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.

public void SaveLogFile(object method, Exception exception)
{
    string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
    try
    {
        //Opens a new file stream which allows asynchronous reading and writing
        using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
        {
            //Writes the method name with the exception and writes the exception underneath
            sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
            sw.WriteLine(exception.ToString()); sw.WriteLine("");
        }
    }
    catch (IOException)
    {
        if (!File.Exists(location + @"log.txt"))
        {
            File.Create(location + @"log.txt");
        }
    }
}

Then to actually write to the error log just write (q being the caught exception)

SaveLogFile(MethodBase.GetCurrentMethod(), `q`);

참고URL : https://stackoverflow.com/questions/5057567/how-do-i-do-logging-in-c-sharp-without-using-3rd-party-libraries

반응형