CHIA SẺ KINH NGHIỆM LẬP TRÌNH – WIKI PAGE

Chúng tôi rất vui mừng được chia sẻ kiến thức sâu sắc về từ khóa Log4net la gi và hy vọng rằng nó sẽ hữu ích cho bạn đọc. Bài viết tập trung trình bày ý nghĩa, vai trò và ứng dụng của từ khóa này trong việc tối ưu hóa nội dung trang web và chiến dịch tiếp thị trực tuyến. Chúng tôi cung cấp các phương pháp tìm kiếm, phân tích và lựa chọn từ khóa phù hợp, cùng với các chiến lược và công cụ hữu ích. Hy vọng rằng thông tin mà chúng tôi chia sẻ sẽ giúp bạn xây dựng chiến lược thành công và thu hút lưu lượng người dùng. Xin chân thành cảm ơn sự quan tâm và hãy tiếp tục theo dõi blog của chúng tôi để cập nhật những kiến thức mới nhất.

LOG4NET là một thư viện mã nguồn mở được cho phép mọi người tiết ra một hoặc nhiều tập tin log, kiểu log cũng như nội dung log một kiểu linh hoạt và thuận tiện. Ngoài ra, Log4net còn rất có thể thay đổi trạng thái log lúc ứng dụng đang làm việc mà không cần ngừng lớp học. Hình như, khi tận dụng log4net sẽ không còn tác động đáng nói đến performance của ứng dụng và điều quan trọng của một thư viện nguồn mở đó là mọi người rất có thể tùy ý phát triển theo nhu yếu của cá thể hoặc tập thể miễn sao thích hợp giấy phép mã nguồn mở.

Bạn Đang Xem: CHIA SẺ KINH NGHIỆM LẬP TRÌNH – WIKI PAGE

Để hiểu được vai trò của việc log, mọi người có một trường hợp như sau; Cty Cửa Hàng chúng tôi đang phát triển một ứng dụng và đã đi đến kỳ hạn phải triển khai cho tất cả những người dùng, đương nhiên do dự án có độ trễ vì thế Cửa Hàng chúng tôi không thể đảm nói rằng những tính năng cũng như toàn bộ khối hệ thống của Cửa Hàng chúng tôi hoạt động và sinh hoạt tốt, ngoài ra có một vài lỗi mà chỉ khi được triển khai thực tiễn mới phát hiện. Vậy người tiêu dùng gặp lỗi khi tận dụng, mà vì khoản cách, vì bảo mật thông tin nên Cửa Hàng chúng tôi khổng thể tiếp cận người tiêu dùng hoặc cài Visual trên máy của họ để DEBUG chưa tính nếu người chạy MultiThread thì rất khó Debug – chỉ mơ hồ biết thông tin về Bug trải qua một người không phải kỹ thuật viên thì phải mất khá lâu để nâng cao được tình hình. Thế thì việc tạo Log trong quy trình người tiêu dùng tận dụng thật sự là một giải pháp tốt – những số lượng biết nói. Tôi chỉ việc yêu cầu người tiêu dùng gửi cho Cửa Hàng chúng tôi file Log và họ sẽ sớm có phiên bản vá lỗi cho vấn của họ.

Để tận dụng được Log4net những người cần lưu ý đến những vấn đề trong tương lai:

* Tập tin thông số kỹ thuật Log4netMăc định tập tin này đó là tập tin thông số kỹ thuật của một ứng dụng dạng [myApp].exe.config hay Web.config cho Asp.NET người cũng rất có thể tạo một file thông số kỹ thuật khác

  • Log ra những dạng nào: ConsoleAppender, FileAppender, RollingFileAppender, AdoNetAppender…
  • Những file log có tính chất gì: file, appendToFile, maximumFileSize, …
  • Những thông tin cho một dòng log: layout, thread, date, level, …

* Phương pháp logLà phương pháp để triển khai việc nhận thông số kỹ thuật và tiến hành tạo log

  • Những thông số kỹ thuật log4net được lưu ở đâu
  • Log những gì và level của log ra sao

Ivàgt; Cấu trúc một file thông số kỹ thuật log4net

Một tập tin thông số kỹ thuật của log4net có cấu trúc giản dị và đơn giản sẽ như dưới, trong đó phần quan trọng là những thẻ <appendervàgt; và thẻ <rootvàgt;

<!- Đó là thư mục gốc của tập tin thông số kỹ thuật của người -> <configurationvàgt; <!- Phần này nên không thay đổi -> <configSectionsvàgt; <section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler, log4net”/> </configSectionsvàgt; <!- Nội dung thông số kỹ thuật -> <log4netvàgt; <!- Level 1 -> <!- Khái niệm Những appender-> <appendervàgt; <!- Level 2 -> <layoutvàgt; <!- Level 3 -> <conversionPattern /> <!- Level 4 -> </layoutvàgt; <filtervàgt; <!- Level 3 -> </filtervàgt; </appendervàgt; <!- Tận dụng những appender-> <rootvàgt; <!- Level 2 -> <level /> <!- Level 3 -> <appender-ref /> <!- Level 3 -> </rootvàgt; </configurationvàgt;

Thẻ <appendervàgt;

Thẻ này quy định những thức trổ tài(lưu trữ) những dòng log, trong đó có 4 cách cơ phiên bản trổ tài: ConsoleAppender, FileAppender, RollingFileAppender, AdoNetAppender, … Cách sử dụng nhất là RollingFileAppender. Hãy để ý thẻ <layoutvàgt;, xem bảng cuối bài để hiểu những tính chất.

RollingFileAppender: Tiết ra tập tin log, khi tập tin này quá giới hạn thì nó sẽ bị thay tên và tạo tập tin mới để log, vậy mọi người sẽ có được nhiều tập tin log.

<!-Log to file collection-> <appender name=”RollingFileAppender” type=”log4net.Appender.RollingFileAppender”> <file value=”mylogfile.txt” /> <prevàgt; <appendToFile value=”true” /> <rollingStyle value=”Size” /> <maxSizeRollBackups value=”5″ /> <maximumFileSize value=”10MB” /> <staticLogFileName value=”true” /> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%date [%thread] %level %logger – %message%newline” /> </layoutvàgt; </appendervàgt;

ConsoleAppender: log ra màng hình, chỉ hiển thị khi ứng dụng có của sổ Console

<!-Log to Console window-> <appender name=”ConsoleAppender” type=”log4net.Appender.ConsoleAppender”> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%date{ABSOLUTE} [%thread] %level %logger – %message%newline”/> </layoutvàgt; <filter type=”log4net.Filter.StringMatchFilter”> <stringToMatch value=”test” /> </filtervàgt; <filter type=”log4net.Filter.DenyAllFilter” /> </appendervàgt;

FileAppender: tiết ra duy nhất một file log

Xem Thêm : “Tìm hiểu” trong tiếng Anh: Định nghĩa, ví dụ

<!-Log to file-> <appender name=”FileAppender” type=”log4net.Appender.FileAppender”> <file value=”mylogfile.log” /> <appendToFile value=”true” /> <lockingModel type=”log4net.Appender.FileAppender+MinimalLock” /> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%date [%thread] %level %logger – %message%newline” /> </layoutvàgt; <filter type=”log4net.Filter.LevelRangeFilter”> <levelMin value=”INFO” /> <levelMax value=”FATAL” /> </filtervàgt; </appendervàgt;

AdoNetAppender: tiết ra những dòng log và lưu vào Database

<!-Log to Database-> <appender name=”AdoNetAppender” type=”log4net.Appender.AdoNetAppender”> <bufferSize value=”100″ /> <connectionType value=”System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ /> <connectionString value=”data source=[database server]; initial catalog=[database name];integrated security=false; persist security info=True;User ID=[user];Password=[password]” /> <commandText value=”INSERT INTO Log ([Date],[Thread],[Level],[Logger], [Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)” /> <parametervàgt; <parameterName value=”@log_date” /> <dbType value=”DateTime” /> <layout type=”log4net.Layout.RawTimeStampLayout” /> </parametervàgt; <parametervàgt; <parameterName value=”@thread” /> <dbType value=”String” /> <size value=”255″ /> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%thread” /> </layoutvàgt; </parametervàgt; <parametervàgt; <parameterName value=”@log_level” /> <dbType value=”String” /> <size value=”50″ /> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%level” /> </layoutvàgt; </parametervàgt; <parametervàgt; <parameterName value=”@logger” /> <dbType value=”String” /> <size value=”255″ /> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%logger” /> </layoutvàgt; </parametervàgt; <parametervàgt; <parameterName value=”@message” /> <dbType value=”String” /> <size value=”4000″ /> <layout type=”log4net.Layout.PatternLayout”> <conversionPattern value=”%message” /> </layoutvàgt; </parametervàgt; <parametervàgt; <parameterName value=”@exception” /> <dbType value=”String” /> <size value=”2000″ /> <layout type=”log4net.Layout.ExceptionLayout” /> </parametervàgt; </appendervàgt;

Trong số đó ý nghĩa những thẻ con của thẻ appender như sau:

Layout

<!- Đó là thẻ mô tả cách hiển thị một dòng log -> <layout type=”log4net.Layout.PatternLayout”> <!- Thẻ này là định dạng của một dòng log, ý nghĩa những ký tự xin xem thêm bảng cuối trang-> <conversionPattern value=”%date [%thread] %-5level %logger [%ndc] – %message%newline”/> </layoutvàgt;

Filter

<!- Thẻ này dùng để làm lọc log-> <!- Start-> <!- Chỉ log nếu dòng log có chữ test, lưu ý rằng StringMatchFilter luôn luôn đi kèm theo DenyAllFilter-> <filter type=”log4net.Filter.StringMatchFilter”> <stringToMatch value=”test” /> </filtervàgt; <filter type=”log4net.Filter.DenyAllFilter”/> <!- End-> <!- Chỉ log trong một giới hạn level-> <filter type=”log4net.Filter.LevelRangeFilter”> <levelMin value=”INFO” /> <levelMax value=”FATAL” /> </filtervàgt; <!- Start-> <!- Chỉ log level ERROR, lưu ý rằng LevelMatchFilterluôn đi kèm theo DenyAllFilter-> <filter type=”log4net.Filter.LevelMatchFilter”> <levelToMatch value=”ERROR”/> </filtervàgt; <filter type=”log4net.Filter.DenyAllFilter”/> <!- End-> <!- Dùng chung với hai trường hợp kể trên-> <filter type=”log4net.Filter.DenyAllFilter”/>

Xem cụ thể về filter tại bài config nâng cao

Level

Mọi người có bảy level sau với mức tối đa ở trên cùng của list, khi người chọn một level để log thì những level từ đó trở lên đều được log:-> OFF – không hề có gì được log-> FATAL-> ERROR-> WARN-> INFO-> DEBUG-> ALL – mọi thứ sẽ tiến hành log

Thẻ <Rootvàgt;

Là thẻ quyết định level nào sẽ tiến hành log và những dạng log sẽ tiến hành tận dụng

<rootvàgt; <level value=”INFO”/> <!- Chỉ log từ level INFO trở lên-> <appender-ref ref=”FileAppender”/> <!- dùng FileAppender-> <appender-ref ref=”ConsoleAppender”/><!- dùng ConsoleAppender-> </rootvàgt;

IIvàgt; Phương pháp log

Khi đã hoàn thành việc tạo file config, mọi người tiến hành chọn thời khắc và nội dung log thích hợp trong Code-behind, mọi người có 4 bước như sau

Xem Thêm : Máy bơm rửa xe đa năng

B1-> Tải thư viện log4net.dll và add vào Project của người, nhớ Reference. Chúng ta cũng có thể tải dll cả mã nguồn ở đây còn tôi thì tôi thích dùng Nuget với command sau

Install-Package log4net

B2-> Hãy khai báo một biến static readonly toàn cục cho tất cả những class cần log, một ví dụ tổng quát dưới

class Program { //Xào luộc dòng code này cho tất cả những class private static readonly log4net.ILog log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { } }

B3-> Chỉ ra tập tin thông số kỹ thuật của log4net, tôi có hai cách thao tác nàyC1) Dán một trong hai dòng code sau vào dòng xoáy dưới cùng của tập tin AssemblyInfo.cs (tìm trong project của người)

//Dùng dòng này nếu tập tin thông số kỹ thuật năm ở một nơi nào đó hoặc không phải tập tin thông số kỹ thuật của ứng dụng [assembly: log4net.Config.XmlConfigurator(ConfigFile = “UsingLog4Net.xml”, Watch = true)] //Dùng dòng code này nếu tập tin thông số kỹ thuật log4net đó là tập tin thông số kỹ thuật của ứng dụng [assembly: log4net.Config.XmlConfigurator(Watch = true)]

C2) Chỉ rõ tập tin thông số kỹ thuật ở thân hàm mà người nghĩ hàm này sẽ tiến hành gọi trước tiên khi ứng dụng được phát động hoặc ít ra là trước lúc tiến hành log ngẫu nhiên thứ gì. Tôi nghĩ đó là hàm Main cho một ứng dụng Console

class Program { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { //Chỉ được sử dụng một trong hai dòng code sau //Dòng này khi sử dụng một tập tin thông số kỹ thuật ngẫu nhiên XmlConfigurator.Configure(new FileInfo(“UsingLog4Net.xml”)); //Dòng này khi sử dụng tập tin thông số kỹ thuật của ứng dụng XmlConfigurator.Configure(); Console.ReadLine(); } }

B4-> Công việc giữ lại là log nơi nào người nghĩ là quan trọng, tùy thuộc vào ý đồ mà chọn level thích hợp

class Program { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { XmlConfigurator.Configure(new FileInfo(“UsingLog4Net.xml”)); log.Info(“Application started”); try { int value = int.Parse(“Tuân”); } catch (Exception e) { log.ErrorFormat(“Error: {0}”,e.Message); } Console.ReadLine(); } }

Trên đó là toàn bộ những gì cở phiên bản nhất để tiến hành tạo log cho một ứng dụng C#, mời người đọc tải về ví dụ tại đây. Ngoài ra người cũng rất có thể xem thêm AppDomain Logging và log4Net and SQLite

Dưới đó là ý nghĩa những giá trị thông tin cho một dòng log được thông số kỹ thuật trong layout, tôi xin phép trích nguyên văn để những người dùng cho đúng chuẩn:

Conversion Patterns

As I mentioned above, the conversion pattern entry is used for the pattern layout to tell the appender how to store the information. There are many different keywords that can be used in these patterns, as well as string literals. Here I will specify what I think are the most useful and important ones. The full list can be found in the log4net documentation.

  • %date – Outputs the date using the local time zone information. This date can be formatted using the curly braces and a layout pattern such as %date{MMMM dd, yyyy HH:mm:ss, fff} to output the value of “January 01, 2011 14:15:43, 767”. However, it is suggested that you use one of the log4net date formatters (ABSOLUTE, DATE, or ISO8601) since they offer better performance.
  • %utcdate – This is the same as the %date modifier, but it outputs in universal time. The modifiers for date/time all work the same way.
  • %exception – If an exception is passed in, it will be entered and a new line will be placed after the exception. If no exception is passed in, this entry will be ignored and no new line will be put in. This is usually placed at the end of a log entry, and usually a new line is placed before the exception as well.
  • %level – This is the level you specified for the sự kiện (DEBUG, INFO, WARN, etc.).
  • %message – This is the message you passed into the log sự kiện.
  • %newline – This is a new line entry. Based upon the platform you are using the application on, this will be translated into the appropriate new line character(s). This is the preferred method to enter a new line and it has no performance problems compared to the platform-specific operators.
  • %timestamp – This is the number of milliseconds since the start of the application.
  • %thread – This will give you the name of the thread that the entry was made on (or the number if the thread is not named).

Beyond these are a few more that can be very useful but should be used with caution. They have negative performance implications and should be used with caution. The list includes:

  • %identity – This is the user name of the current user using the Principal.Identity.Name method.
  • %location – Especially useful if you are running in Debug mode, this tells you where the log method was called (line number, method, etc.). However, the amount of information will decrease as you operate in Release mode depending on what the system can access from the compiled code.
  • %line – This is the line number of the code entry (see the note above on the location issues).
  • %method – This is the method that calls the log entry (see the note above on the location issues).
  • %username – This outputs the value of the WindowsIdentity property.

You may notice that some config files have letters instead of names. These have been depreciated in favor of whole word entries lượt thích I have specified above. Also, while I won’t cover it in depth here, note that each of these entries can be formatted to fit a certain width. Spaces can be added (to either side) and values can be truncated in order to fit inside of fixed-width columns. The basic syntax is to place a numeric value or values between the % sign and the name. Here are the modifiers:

  • X – Specifies the minimum number of characters. Anything that has fewer characters will have spaces placed on the left of the value to equal 20 characters including the message. For example, %10messagewill give you ” hi“.
  • -X – Same as above, only the spaces will be placed on the right. For example, %-10message will give you “hi “.
  • .X – Specifies the maximum number of characters. The important thing to note is that this will truncate the beginning of the string, not the end. For example, %.10message will give me “rror entry” if the string passed in was “Error entry“.

You can put all of this together with something lượt thích this: “%10.20message“, which would specify that if the message isn’t ten characters long, put spaces on the left to fill it out to ten characters, but if the message is more than 20 characters long, cut off the beginning to make it only 20 characters.

You May Also Like

About the Author: v1000