Tuesday, January 16, 2018

ASP.NET Core 2.0 - Logging with Log4Net (Microsoft.Extensions.Logging.Log4Net.AspNetCore)


Below are steps in integrating Log4Net in Asp.Net Core.

1) First install required package:
    dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore
2) Create file log4net.config with following xml content

    <?xml version="1.0" encoding="utf-8" ?>
    <log4net>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file type="log4net.Util.PatternString" value="Logs/Logs_%date{yyyyMMdd}.txt" />
        <rollingStyle value="Date" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <datePattern value="yyyyMMdd" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="10000KB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
        </layout>
      </appender>
      <root>
        <appender-ref ref="RollingFileAppender" />
        <level value="All" />
      </root>
    </log4net>
3) Inside Appsetting.js add section to save log4net config path ,section is added on same level as "Logging"

  "Log4NetConfigFile": {
    "Name": "Services/LoggingService/log4net.config"
  }

    My log4net.config is inside services/LoggingService you can add it in project root if so section will need tiny modification in path as below.

    "Log4NetConfigFile": {
        "Name": "log4net.config"
      }
     

3) inside Configure method in StartUp.cs add

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddLog4Net(Configuration.GetValue<string>("Log4NetConfigFile:Name"));

4) Inside Your Test controller add class variable
    private readonly ILogger Logger;

   and inject its dependency through constructor

public TestController(ILoggerFactory DepLoggerFactory, IHostingEnvironment DepHostingEnvironment)
        {
            HostingEnvironment = DepHostingEnvironment;
            Logger = DepLoggerFactory.CreateLogger("Controllers.TestController");
        }

5) Now Create Test Action


     public IActionResult  GetAllMyModels(string id)
        {
            var comments = (from m in Db.MyModelChild
                            where m.ParentId.ToString() == id
                            select m).ToList();

            Logger.LogInformation("Test log information 001");
            if (comments.Count() == 0)
            {
                Logger.LogInformation("Test log information 002");
                return NotFound();
            }
            return new ObjectResult(comments);
        }

      on success this method emit MyModelChild objects as json

6) Now check to Logs folder in root redirectory its created with pattern of YYYYMMDD prepended with "Logs_"
    Logs_20180116.txt.Logged text also include timestamp.
   
    Output:
        INFO  16-13-2018 11:13:24 Controllers.TestController [7] - Test log information 001

        In my case i am getting data so above log text will be there along with other output from dotnet run which falls in info.
   
     we can write other kind of log than warning too.

Saturday, January 6, 2018

Serializing & deserializing an object to & from JSON


Dot net framework 3.5 has native support for serializing an object into JSON string.to illustrate this we will create a console application,in this console application we will first create a simple entity class called device with properties devicename,brandname,price,resolution & devicecode.
  Now in our console's main we will create a LIST based collection from our Device class.
 To serialise this collection object we are using functionality from system.web.script namespace which requires adding reference to corresponding dll.
  We created two static function one or purpose of serializing namely SerializeJsonToString & other for purpose of deserializing namely DeSerializeJsonStringToObj.
  For serializing we need to create an object of JavaScriptSerializer class which has method Serialize() which will take an object and convert it into equivalent JSON string.
   For deserialization we will use  Deserialize() method to which we first need which type of object we are deserializing in our case it is List<Device>  which is LIST based collection of Device objects.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;



namespace JsonSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            Device Note3 = new Device { DeviceName = "Samsung Galaxy Note III", BrandName = "Samsung", Price = "43,787", Resolution = "1024X768", DeviceCode = "GTN623" };
            Device Note2 = new Device { DeviceName = "Samsung Galaxy Note II", BrandName = "Samsung", Price = "33,250", Resolution = "800X600", DeviceCode = "GTN523" };
            Device Mega = new Device { DeviceName = "Samsung Galaxy Mega", BrandName = "Samsung", Price = "23,787", Resolution = "600X425" ,DeviceCode="GTN123"};
            Device Lumia = new Device { DeviceName = "Nokia Lumia 520", BrandName = "Nokia", Price = "20,787", Resolution = "600X425" };



            List<JsonSerialization.Device> DeviceList = new List<JsonSerialization.Device>();
            DeviceList.AddRange(new Device[] { Note3, Note2, Mega, Lumia });



            string SerializedString = SerializeJsonToString(DeviceList);



            List<Device> DeserialzedDeviceList = new List<Device>();
            DeserialzedDeviceList = DeSerializeJsonStringToObj(SerializedString);
      
            Console.ReadKey();
        }



        public static string SerializeJsonToString(List<JsonSerialization.Device> obj2Serialize)
        {
            JavaScriptSerializer oSerializer = new JavaScriptSerializer();
            string sJSON = oSerializer.Serialize(obj2Serialize);
            return sJSON;
        }
        public static List<Device> DeSerializeJsonStringToObj(string jsonString)
        {
            JavaScriptSerializer oSerializer = new JavaScriptSerializer();
            List<Device> DeserialzedDeviceList  = oSerializer.Deserialize<List<Device>>(jsonString);
            return DeserialzedDeviceList;
        }
    }



    //entity class
    public class Device
    {
        public string DeviceName 
        { 
            get; set; 
        }
        public string BrandName
        {
            get; set; 
        }
        public string DeviceCode 
        { 
            get; set; 
        }
        public string Price
        {
            get;
            set;
        }



        public string Resolution
        {
            get;
            set;
        }
    }
}