Privacy Info

Sunday, October 9, 2022

Website Monitor - Console Application


Monitoring whether websites are working fine are not is very difficult task. Especially manually checking the sites is practically impossible. To solve this problem I discovered solution Website Monitor. It is ASP.NET Console Application which will check whether application is up and running if not it will log the error. This post will explain you how can you create this application.

1. Create Console Application in Visual Studio

2. Install below two Nugget package for your project

    log4net


    Newtonsoft.Json


3. Add Reference for log4net in AssemblyInfo.cs file 


Code

[assembly: log4net.Config.XmlConfigurator(Watch = true)]


4. Add below code in App.config file

Code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
	</configSections>
	<!-- Log4net Logging Setup Start -->
	<log4net>
		<root>
			<level value="ALL" />
			<appender-ref ref="console" />
			<appender-ref ref="file" />
		</root>
		<appender name="console" type="log4net.Appender.ConsoleAppender">
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date %level - %message%newline" />
			</layout>
		</appender>
		<appender name="file" type="log4net.Appender.RollingFileAppender">
			<file type="log4net.Util.PatternString" value="Logs/WebsiteMonitor_%date{yyyy.MM.dd_HH.mm.ss}.log" />
			<appendToFile value="true" />
			<rollingStyle value="Once" />
			<maxSizeRollBackups value="5" />
			<staticLogFileName value="false" />
			<maximumFileSize value="10MB" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date %level - %message%newline" />
			</layout>
		</appender>
	</log4net>
	<!-- Log4net Logging Setup End -->
	<startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
	<appSettings>
		<add key="UrlsFilePath" value="Urls.json"/>
	</appSettings>
</configuration>

Note: You can change log4net configurations as per your requirement.

5. Create Logs folder in the application and set below actions.


6. Create Logger.cs file and add below code.

Code

namespace SitesMonitor
{
    public static class Logger
    {
        public static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    }
}


7. Create Urls.json file and add below code.

Code

[
  {
    "url": "https://www.google.com"
  },
  {
    "url": "https://www.amazon.com"
  },
  {
    "url": "https://www.flipkart.com"
  },
  {
    "url": "https://www.youtube.com"
  },
  {
    "url": "https://bookmyshow.com"
  }
]

8. Change Build Actions of Urls.json as shown below



9. Create JsonUrls.cs file and add below code

Code

using System;
using System.Collections.Generic;

namespace SitesMonitor
{
    public  class JsonUrls
    {
        public string url { get; set; }

        public static List<JsonUrls> GetSiteUrls()
        {
            List<JsonUrls> URLS = new List<JsonUrls>();
            try
            {
                string UrlsFilePath = System.Configuration.ConfigurationManager.AppSettings["UrlsFilePath"].ToString();

                //Getting URLS from Json File
                string json = System.IO.File.ReadAllText(UrlsFilePath);
                URLS = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JsonUrls>>(json);

            }
            catch (Exception ex)
            {
                Logger.Log.Error(String.Format("{0}  Exception {1}", DateTime.Now, ex));
            }

            return URLS;
        }
    }
}


10. Add below Code in Program.cs file

Code

using System;
using System.Collections.Generic;
using System.Net;

namespace SitesMonitor
{
    internal class Program
    {
        static void Main(string[] args)
        {
            StartApplication();
        }

        private static void StartApplication()
        {
            try
            {
                Logger.Log.Info(String.Format("Execution Started {0}", DateTime.Now));
List<JsonUrls> URLS = JsonUrls.GetSiteUrls(); foreach (var URL in URLS) { string url = URL.url; WebRequest request = WebRequest.Create(url); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response != null || response.StatusCode == HttpStatusCode.OK) { //Website is working fine Logger.Log.Info(String.Format("{0} URL:{1} Status Code:{2} Status Description:{3}", DateTime.Now, url, response.StatusCode, response.StatusDescription)); } else { //Error occured for website Logger.Log.Info(String.Format("{0} URL:{1} Status Code:{2} Status Description:{3}", DateTime.Now, url, response.StatusCode, response.StatusDescription)); } } catch (Exception ex) { Logger.Log.Error(String.Format("{0} URL:{1} Exception {2}", DateTime.Now, url, ex)); } } } catch (Exception ex) { Logger.Log.Error(String.Format("{0} Exception {1}", DateTime.Now, ex)); } finally { Logger.Log.Info(String.Format("Execution Completed {0}", DateTime.Now)); Console.ReadLine(); } } } }


Finally you Solution will look like this.



Console Output


Log File




Your Console Application is ready for use. You can also deploy this console application in Windows Task scheduler and it will run after certain duration. Also, you can configure Email/SMS alerts whenever site is down.


Hope you find this information useful. 😀


No comments:

Post a Comment

Sitecore PowerShell Script - Remove item from Workflow

We came across scenario where we need to remove multiple items from workflow. If items would be less then there would not be any issue but i...