Custom Implementation of log4net httpappender

Source: Internet
Author: User
Tags log4net

Log4net has many built-in appender, but it does not seem to be found based on HTTP. when the application wants to save logs locally, it can also submit the logs to an HTTP service for unified tracking and management. if every record of logs is submitted to the HTTP service, connection creation on the application end is very performance-consuming. because logs do not require real-time synchronization, they can be submitted at a scheduled time or when the memory log reaches a certain number, so that the performance problems caused by frequent log submission will not occur.

Function Definition

Implementing an appender in log4net is a simple task. You only need to implement the iappender interface. Of course, log4net will also provide some basic classes for our implementation. next we will implement an httpappender. before implementation, you need to set some parameters for internal implementation.

Host log submission URL, for example, http: // localhost: 30532/logupload. aspx

Servertag: the server tag for submitting logs, for example, 192.168.0.1.

Appname ApplicationProgramFor example, game

The maximum number of records stored in maxrecords memory. When the number of logs exceeds the threshold, data is submitted.

Timer timed submission time

Message Storage Structure
     Public   Class Logevent {  Public  Logevent () {errors = New List <eventmessage> ();}  Public   String  Eventtype {  Get  ;  Set  ;}  Public   String Servertag {  Get  ;  Set  ;}  Public   String  Message {  Get  ;  Set  ;}  Public   String  Appname { Get  ;  Set  ;}  Public  Datetime errortime {  Get  ;  Set  ;}  Public List <eventmessage> Errors {  Get  ;  Set ;}} 
 
Public class eventmessage {Public String message {Get; set;} Public String stacktrace {Get; Set ;}}
Appender implementation
     ///   <Summary>      ///   <Code>      ///   <Appender name = "httpappender" type = "log4netuts. httpappender, log4netuts">      ///    <Param name = "host" value = "http: /localhost: 30532/webform1.aspx"/>      ///   <Param name = "servertag" value = "192.168.0.1"/>      ///    <Param name = "appname" value = "test"/>      ///    <Param name = "timer" value = "10000"/>      ///    <Param name = "maxrecords" value = "1000"/>      ///   </Appender>      ///   </Code>      ///   </Summary>      Public  Class  Httpappender: log4net. appender. appenderskeleton {  Public  Httpappender () {Timer = 5000  ; Maxrecords = 300  ;}  Private  System. Threading. Timer mtimer;  Private   Void  Createtime (){ Lock ( This  ){  If (Mtimer = Null  ) Mtimer = New System. Threading. Timer (upload, Null  , Timer, timer );}}  Private   Readonly   Static Type declaringtype = Typeof (Httpappender );  Private Queue <logevent> mevents = New Queue <logevent> ( 1000  );  Private   Void  Add (logevent item) {createtime ();  Lock  (Mevents) {mevents. enqueue (item );  If (Mevents. Count> Maxrecords) Upload ( Null  );}}  Private   Void Upload ( Object  State) {list <Logevent> items = New List <logevent> ();  Lock  (Mevents ){  While (Mevents. Count> 0 ) {Items. Add (mevents. dequeue ());}}  If (Items. Count> 0  ) {Onupload (items );}}  Private   Void Onupload ( Object  State ){  Try  {List <Logevent> items = (list <logevent> ) State; String Param = "  Logdata =  " + Newtonsoft. JSON. jsonconvert. serializeobject (items );  Byte [] DATA = Encoding. utf8.getbytes (PARAM); httpwebrequest req = (Httpwebrequest) httpwebrequest. Create (host); Req. Method = "  Post  "  ; Req. contenttype = "  Application/X-WWW-form-urlencoded  "  ; Req. contentlength = Data. length;  Using (Stream reqstream = Req. getrequeststream () {reqstream. Write (data,  0  , Data. Length );}  Using (Webresponse wR = Req. getresponse ()){}} Catch  (Exception E _) {loglog. Error (declaringtype, E _. Message );}}  Public   String  Host {  Get  ;  Set  ;}  Public   String  Servertag {  Get  ; Set  ;}  Public   String  Appname {  Get  ;  Set  ;}  Public   Int  Maxrecords {  Get  ;  Set  ;} Public   Int  Timer {  Get  ;  Set  ;}  Protected   Override   Void  Append (log4net. Core. loggingevent ){  Try  {Logevent le = New Logevent (); Le. errortime = Loggingevent. timestamp; Le. eventtype = Loggingevent. level. tostring (); Le. Message = Loggingevent. renderedmessage; Le. appname = Appname; Le. servertag = Servertag; adderror (Le, loggingevent. exceptionobject); add (LE );}  Catch  (Exception E _) {loglog. Error (declaringtype, E _. Message );}} Private   Void  Adderror (logevent E, exception ERR ){  If (Err! = Null  ) {E. errors. Add (  New Eventmessage {message = err. Message, stacktrace = Err. stacktrace}); err = Err. innerexception;  While (Err! = Null  ) {E. errors. Add ( New Eventmessage {message = err. Message, stacktrace = Err. stacktrace}); err = Err. innerexception ;}}}} 

ImplementationCodeIt is relatively simple to package the data in the queue in JSON format and upload it to the relevant HTTP service.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.