.NET 도움말 NLog C# (How it Works for Developers) 커티스 차우 업데이트됨:6월 22, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 Logging is an essential aspect of software development. It helps developers track the behavior of their applications, troubleshoot issues, and gain insights into how their code is performing in various environments. NLog is a popular logging framework for C# that makes it easy to implement robust and flexible logging in your applications. In this comprehensive guide and tutorial, we will explore the world of NLog in C#. What is NLog? NLog is a free, open-source logging library for .NET and .NET Core applications. It provides a flexible and highly configurable way to log messages in your application. NLog is a widely used free logging platform in the .NET ecosystem due to its performance, extensibility, and ease of use. Getting Started with NLog We can use NLog in ASP.NET Web Applications, ASP.NET WEB APIs, Windows Form Applications, ASP.NET MVC Applications, or any kind according to our needs. We will use the Console Application to demonstrate all the use cases. Install NLog Nuget Package To get started with NLog, you'll need to install the NLog NuGet package in your project. You can do this via the NuGet Package Manager in Visual Studio by following the steps: In the "Tools" menu select "NuGet Package Manager," then choose "Manage NuGet Packages for Solution." Or, right-click on your project in the Solution Explorer, select "Manage NuGet Packages," and choose "Browse." In the NuGet Package Manager window, click on the "Browse" tab, and in the search box, type "NLog." You should see the NLog package in the search results. Click on it to select it. On the right side of the NuGet Package Manager window, there is a list of projects in your solution. Select the project(s) where you want to install NLog. Choose the desired version of the NLog package from the version dropdown. You can select the latest stable version or a specific version if needed. After selecting the project(s) and the version, click the "Install" button to start the installation process. The NuGet Package Manager will download and install NLog and any dependencies. You will see the progress in the output window. NLog is now successfully installed in your project, and you can start using it for logging within your C# code. Create NLog Configuration file To create an NLog configuration file (typically named nlog.config), you can follow these steps. This configuration file will specify how NLog should behave in your application, including log targets, layout renderers, and rules. In your project, right-click on the project or the desired folder where you want to create the configuration file. Choose "Add" > "New Item..." In the "Add New Item" dialog, search for "XML File" or "XML" and select it. Name the file nlog.config and click the "Add" button. Open the newly created nlog.config file in a text editor or XML editor. Add the following configuration in the NLog.XML file. Below is a basic example of an NLog configuration that logs messages to a Console target. You can customize this Config File to suit your needs: Config file <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="console" xsi:type="Console" layout="${longdate}|${message}"/> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="console" /> </rules> </nlog> <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="console" xsi:type="Console" layout="${longdate}|${message}"/> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="console" /> </rules> </nlog> XML In your C# code, make sure you load the NLog configuration from the nlog.config file. You typically do this in the application's startup code, such as in an ASP.NET Core Startup.cs(for .NET Version same or older than .NET 5), program.cs file (for .NET 6 or later version), or a console application's Main method: using NLog; internal class Program { // Create an instance of the Logger private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { // Log a debug message logger.Debug("This is a Debug Message"); // Pause the console for viewing output Console.Read(); } } using NLog; internal class Program { // Create an instance of the Logger private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { // Log a debug message logger.Debug("This is a Debug Message"); // Pause the console for viewing output Console.Read(); } } $vbLabelText $csharpLabel The output of the above program is as shown: In this example, we create an instance of the Logger class and use it to log messages at the Debug Level. Let's explore the tracing level supported by NLog. Logging Levels NLog supports several logging levels, each with its own significance: Trace: The most detailed level, typically used for diagnostic purposes. Debug: Used for debugging information that can be helpful during development. Info: General information about the application's operation. Warn: Indicates a potential issue that does not disrupt the application. Error: Indicates a failure that should be investigated but doesn't necessarily crash the application. Fatal: Indicates a critical failure that should be addressed immediately. By categorizing log messages into these levels, you can easily filter and prioritize them based on their severity. Set minlevel="Trace" in the rules tag in your nLog.Config file as shown below. <rules> <logger name="*" minlevel="Trace" writeTo="console" /> </rules> <rules> <logger name="*" minlevel="Trace" writeTo="console" /> </rules> XML Let's write code to log messages of all tracing levels. using NLog; internal class Program { // Create an instance of the Logger private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { // Log messages of different tracking levels logger.Trace("This is a Trace Message"); logger.Debug("This is a Debug Message"); logger.Info("This is an Info Message"); logger.Warn("This is a Warning Message"); logger.Error("This is an Error Message"); logger.Fatal("This is a Fatal Message"); // Pause the console for viewing output Console.Read(); } } using NLog; internal class Program { // Create an instance of the Logger private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { // Log messages of different tracking levels logger.Trace("This is a Trace Message"); logger.Debug("This is a Debug Message"); logger.Info("This is an Info Message"); logger.Warn("This is a Warning Message"); logger.Error("This is an Error Message"); logger.Fatal("This is a Fatal Message"); // Pause the console for viewing output Console.Read(); } } $vbLabelText $csharpLabel Our Program has logged messages in the Console as shown below. Now, We have demonstrated the example of logging messages in the Console. Now we will configure an NLog target to log messages in the file. Log Message in File We need to set a file target instead of a Console target in our config file for file logging. <targets> <target xsi:type="File" name="fileTarget" fileName="D:\Logs\mylog.txt" layout="${longdate} ${level:uppercase=true} ${message}" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="fileTarget" /> </rules> <targets> <target xsi:type="File" name="fileTarget" fileName="D:\Logs\mylog.txt" layout="${longdate} ${level:uppercase=true} ${message}" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="fileTarget" /> </rules> XML Now, run the program to log messages in a file. Logging targets NLog supports various log output targets, allowing you to choose where your log messages should be stored. Some common targets include: File: Logs messages to one or more files. Console: Logs messages to the console. Database: Logs messages to a database (SQL Server, MySQL, Oracle, PostgreSQL, etc.) table. Email: Sends log messages as emails. Event Log: Logs messages to the Windows Event Log. Custom Targets: You can create custom log targets to fit your specific needs. You can configure NLog to use one or more targets simultaneously. Introducing IronPDF Explore Further about IronPDF is a powerful .NET library that simplifies PDF handling in C# and VB.NET applications. It provides robust capabilities for creating, editing, and manipulating PDF documents, as well as converting HTML content to PDF format, making it an essential tool for developers across a wide range of industries, including web development, reporting, and document management. IronPDF’s standout feature is its HTML to PDF Conversion function, which keeps your layouts and styles preserved. It generates PDFs from web content, making it ideal for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be easily converted to PDFs. using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 1. Convert HTML String to PDF var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"; var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent); pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf"); // 2. Convert HTML File to PDF var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath); pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf"); // 3. Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 1. Convert HTML String to PDF var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"; var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent); pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf"); // 2. Convert HTML File to PDF var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath); pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf"); // 3. Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } $vbLabelText $csharpLabel Let's generate a PDF with logging. PDF Generation with Logging The first step is to install the IronPDF library into our project. We can do this using the NuGet Package Manager in Visual Studio or via the NuGet CLI. Open your project and write the following command in the Package Manager Console. Install-Package IronPdf This command will install IronPDF with all required dependencies in our project. Write the following code to generate a PDF File from HTML with logging. using NLog; using IronPdf; internal class Program { // Create an instance of the Logger private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { logger.Info("Initializing Chrome PDF Renderer"); ChromePdfRenderer renderer = new ChromePdfRenderer(); logger.Info("Creating PDF From HTML String"); var pdf = renderer.RenderHtmlAsPdf("<h1>This is my Sample PDF<h1>"); logger.Info("Saving PDF File"); pdf.SaveAs(@"D:\myPDF.pdf"); } } using NLog; using IronPdf; internal class Program { // Create an instance of the Logger private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { logger.Info("Initializing Chrome PDF Renderer"); ChromePdfRenderer renderer = new ChromePdfRenderer(); logger.Info("Creating PDF From HTML String"); var pdf = renderer.RenderHtmlAsPdf("<h1>This is my Sample PDF<h1>"); logger.Info("Saving PDF File"); pdf.SaveAs(@"D:\myPDF.pdf"); } } $vbLabelText $csharpLabel The above code snippet will create a PDF file with a logged message in the file as shown below. Log and PDF File Conclusion In conclusion, NLog has emerged as an essential tool for effective logging in C# applications, offering developers a robust framework for capturing, categorizing, and managing log data. Its flexibility and ease of use make it a go-to choice for logging needs across various domains. Furthermore, when combined with complementary libraries like IronPDF, which simplifies PDF generation and manipulation in .NET applications, developers can extend their management capabilities to encompass the creation of PDF-based logs and reports. It's worth mentioning that IronPDF offers a free trial of IronPDF for testing its features. If it meets your requirements, you can opt for a commercial license for IronPDF, providing continued access to IronPDF's capabilities with added benefits and support for seamless integration into your projects, especially for PDF-related functionalities. By employing the power of NLog and IronPDF together, developers can not only gain insights into their application's behavior but also enhance their reporting and document management processes, ensuring that their software remains efficient, maintainable, and well-documented structured logging. 자주 묻는 질문 NLog는 C# 애플리케이션에서 로깅을 어떻게 개선하나요? NLog는 C# 애플리케이션을 위한 강력하고 유연한 로깅 프레임워크를 제공합니다. 개발자는 구성 파일에서 로그 대상과 규칙을 정의하여 추적, 디버그, 정보, 경고, 오류, 치명적 등 다양한 로깅 수준을 지원함으로써 로깅을 쉽게 구현할 수 있습니다. .NET 애플리케이션에서 NLog를 설정하는 프로세스는 무엇인가요? .NET 애플리케이션에서 NLog를 설정하려면 NLog NuGet 패키지를 설치하고 nlog.config 파일에서 로깅 대상 및 규칙을 구성해야 합니다. 이 설정을 통해 파일, 콘솔, 데이터베이스 또는 이메일 등 로그를 보낼 위치를 지정할 수 있습니다. NLog를 사용하여 데이터베이스에 메시지를 기록하려면 어떻게 해야 하나요? NLog를 사용하여 데이터베이스에 메시지를 기록하려면 nlog.config 파일에서 데이터베이스 대상을 설정해야 합니다. 연결 문자열과 로그 항목에 필요한 테이블 또는 저장 프로시저 세부 정보를 지정합니다. 이메일을 통해 로그 메시지를 보내는 데 NLog를 사용할 수 있나요? 예, nlog.config 파일에서 이메일 대상을 구성하여 이메일을 통해 로그 메시지를 보낼 수 있습니다. SMTP 서버 세부 정보, 수신자 이메일 주소 및 기타 이메일 설정을 제공해야 합니다. .NET에서 PDF 생성에 IronPDF를 사용하면 어떤 이점이 있나요? IronPDF는 PDF 생성, 편집 및 변환을 간소화하는 강력한 .NET 라이브러리입니다. HTML에서 PDF로의 변환을 지원하여 개발자가 HTML 문자열, 파일 또는 URL에서 PDF를 생성하여 보고 및 문서 관리 프로세스를 향상시킬 수 있습니다. C# 애플리케이션에서 로깅과 PDF 생성을 통합하려면 어떻게 해야 하나요? C# 애플리케이션에서 NLog를 사용하여 애플리케이션 이벤트를 로깅하고 IronPDF를 사용하여 PDF를 생성함으로써 NLog와 IronPDF를 통합할 수 있습니다. 이 조합을 사용하면 로그 정보가 포함된 상세한 PDF 보고서를 만들 수 있습니다. NLog 구성 문제에 대한 일반적인 문제 해결 단계는 무엇인가요? NLog 구성 문제에 대한 일반적인 문제 해결 단계에는 nlog.config 파일에 구문 오류가 있는지 확인하고, 로그 대상의 파일 경로와 권한이 올바른지 확인하고, 애플리케이션에서 로깅에 영향을 줄 수 있는 예외가 있는지 확인하는 것이 포함됩니다. 구매하기 전에 IronPDF의 기능을 테스트하려면 어떻게 해야 하나요? IronPDF는 개발자가 기능을 테스트할 수 있는 무료 평가판을 제공합니다. 이 평가판은 상용 라이선스를 선택하기 전에 IronPDF의 PDF 생성, 편집 및 변환 기능을 평가할 수 있는 기회를 제공합니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 C# Ref Keywords (How it Works for Developers)Entity Framework C# (How it Works f...
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기