87728

How to get all log information in web API 2 using log4net

Question:

I have created a WEB API. Now I want to make a log file in which I want to get all the API log information. For this, by using <a href="https://www.youtube.com/watch?v=RZx1g5oWmMk" rel="nofollow">log4net</a> I have created a log file.

<ol><li>Downloaded it from NuGet.</li> <li>

Add log4net in web.config file

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> <log4net> <root> <appender-ref ref ="LogFileAppender"/> </root> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="E:\MyLog\LogFile.txt"/> <param name="AppendToFile" value ="false"/> <rollingStyle value="Size"/> <maxSizeRollBackups value="10"/> <maximumFileSize value="5MB"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %meesage%newline"/> </layout> </appender> <logger name="ApiLog"> <level value="DEBUG"/> </logger> </log4net> </li> <li>

In my Global.asax.cs file

private static readonly ILog log = LogManager.GetLogger("ApiLog");

protected void Application_Start() { log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config"))); } protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); log.Debug("++++++++++++++++++++++++++++"); log.Error("Exception - \n" + ex); log.Debug("++++++++++++++++++++++++++++"); } </li> </ol>

<strong>Controller</strong>

public class MetersController : ApiController { public mdcEntities mdcEntitites = new mdcEntities(); public HttpResponseMessage GetByMsn(string msn, DateTime dt) { try { var dateTime = dt.AddHours(-1); var result = mdcEntitites.tj_xhqd.Where(m => (m.zdjh == msn) && (m.sjsj >= dateTime)) .OrderByDescending(o => o.sjsj) .Select(s => s.sjsj) .FirstOrDefault(); DateTime resulted = new DateTime(); DateTime userSent = new DateTime(); resulted = Convert.ToDateTime(result); userSent = Convert.ToDateTime(dt); double diff = Math.Abs((resulted - userSent).TotalMinutes); if (diff <= 10) { return Request.CreateResponse(HttpStatusCode.OK, new { data = new { Response = "Yes" } }); } else { return Request.CreateResponse(HttpStatusCode.OK, new { data = new { Response = "No" } }); } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } } }

Now when I run this API, it did create a log file but it's empty because it will only log for errors.

How can I see my all process log including start and end timeline?

Any help would be highly appreciated

Answer1:

If you want log for all method you need to add log at start & end of each method like :

public HttpResponseMessage GetByMsn(string msn, DateTime dt) { try { Log.Debug(String.Format("{0} started", MethodBase.GetCurrentMethod().Name;)); ... Log.Debug(String.Format("{0} succeeded", MethodBase.GetCurrentMethod().Name;)); } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } }

<strong>OR</strong>

alternative need <strong>custom action filter</strong> that triggers log after each method like given in below link:

<a href="https://www.c-sharpcorner.com/UploadFile/db2972/trace-web-api-execution-time-using-custom-action-filter/" rel="nofollow">https://www.c-sharpcorner.com/UploadFile/db2972/trace-web-api-execution-time-using-custom-action-filter/</a>

Recommend

  • collectionView(_:didDeselectItemsAt:) is never called
  • Swift iOS: -How to exclude .livePhotos from inclusion in the PHFetchOptions?
  • Java.lang.SecurityException:SECURE PERMISSION in android?
  • Log4J: Warn No Appenders could be found for Logger error
  • Log4j stops logging in a File(File Appenders) when i open/edit the File?
  • Logj4 is not loaded if application is deployed as a war archive
  • Web Api 2 get controller and action name in OWIN middleware?
  • log4net %property does not work
  • Create multiple Logfiles with dynamic Names with log4net
  • JRule is showing all sorts of error in rule team server , but works good in Rule Studio
  • Why isn't my log4j.properties file getting used?
  • Return control to function when modal viewcontroller dismissed
  • how to configure log file path to current working target directory in log4j2 xml format
  • log4Net in Windows Forms App does not write log file
  • Log4net writing custom object to sql database using custom appender?
  • ASP.NET MVC Routing strategy for static content for each View
  • How to redirect to home page after session timeout
  • Web API Basic Auth inside an MVC app with Identity Auth
  • IsAuthenticated is false! weird behaviour + review question
  • Hatch area using pcolormesh in Basemap
  • How to edit a Word document that opens in read-mode in VBA
  • java.net.SocketTimeoutException on embedded tomcat with jersey
  • Why isn't \\\\ interpreted as a blackslash in this regex?
  • Log4j cannot find properties file in a simple application
  • DependencyObject.AssociatedObject is always null
  • NRefactory: How do I access unresolved Named Arguments on a Property Attribute?
  • Updating Dojo provide
  • Defined variables not working in javascript files when I use getScript
  • How to getText() from the input field of an angularjs Application
  • Disable Kendo Autocomplete
  • How can I display the parent menu item's description using Wordpress walkers?
  • Can I check if a recipient has an automatic reply before I send an email?
  • Getting last autonumber in access
  • Azure Cloud Service Web Role web pages do not load
  • sending/ receiving email in Java
  • How to delete a row from a dynamic generate table using jquery?
  • Proper way to use connect-multiparty with express.js?
  • -fvisibility=hidden not passed by compiler for Debug builds
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Checking variable from a different class in C#