ASP.NET Core provides us a rich Logging APIs which have a set of logger providers including: ConsoleLoggerPtoviderAzureAppServicesDiagnosticsLoggerProviderEventLogLoggerProvider and much more.

This let C# developers happy than before, because you need to implement them loggers yourself in the past, however a lot of us writing JavaScript code in almost web applications which is little hard, but find the client-side exceptions & errors are even harder.

There are many client-side loggers that you can name it, which are fit our needs, but today I wanna talk about the client-side logging from different angle. Me and you as developers suffer a lot from unexpected javascript error that happen occasionally, sometimes the reason is silly such missing a curly braces or broke a link .. etc.

With that I was thinking last few days that it would be nice to integrate the client-side & server-side logs, so all the logs will be logged from the ASP.NET Core logger providers that we like and love instead of managing two different logger providers for both client-side & server-side.

Logging JavaScript Events

Basically the idea is very simple, I need to inject the client-side logging APIs script into our view, after that I need the JavaScriptLoggingMiddleware to listening to the upcoming script logs and forward them to ASP.NET Core logger providers.

With that we're ready to show some code, but before that I need to mention that I didn't introduce a new logging APIs, but I could, so the javascript console object is enough for logging. In both cases we need to intercept the console logs as the following:

(function () {
var trace = console.trace;
var debug = console.debug;
var info = console.info;
var warn = console.warn;
var error = console.error; console.trace = function (message) {
log(logLevel.Trace, message);
trace.call(this, arguments);
}; console.debug = function (message) {
log(logLevel.Debug, message);
debug.call(this, arguments);
}; console.info = function (message) {
log(logLevel.Information, message);
info.call(this, arguments);
}; console.warn = function (message) {
log(logLevel.Warning, message);
warn.call(this, arguments);
}; console.error = function (message) {
log(logLevel.Error, message);
error.call(this, arguments);
};
})();

The log is a method that I created to post the actual logs to the server, which will handled by the JavaScriptLoggingMiddleware that shown below.

At this point I was wondering whether to store jsLogger script into the disk and render it using a tag helper or not!! after awhile I inspired by Application Insights and decided to store it into a resx file and retrieve them later using JavaScriptLoggingSnippet.

public class JavaScriptLoggingMiddleware
{
private readonly ILogger _logger;
private readonly RequestDelegate _next; public JavaScriptLoggingMiddleware(ILoggerFactory loggerFactory, RequestDelegate next)
{
_logger = loggerFactory.CreateLogger<JavaScriptLoggingMiddleware>();
_next = next;
} public async Task Invoke(HttpContext context)
{
if (context.Request.Path == "/log" && context.Request.Method == "POST" && context.Request.HasFormContentType)
{
var form = await context.Request.ReadFormAsync();
var level = Convert.ToInt32(form["level"].First());
var message = form["message"].First(); switch ((LogLevel)level)
{
case LogLevel.Trace:
_logger.LogTrace(message);
break;
case LogLevel.Debug:
_logger.LogDebug(message);
break;
case LogLevel.Information:
_logger.LogInformation(message);
break;
case LogLevel.Warning:
_logger.LogWarning(message);
break;
case LogLevel.Error:
_logger.LogError(message);
break;
default:
return;
}
}
else
{
await _next(context);
}
}
}

If you look closely to the code above, you will notice that the middleware listening for specific url, when it hit I need to map the client-side log levels with the server-side once, after that I log them normally.

I can finally log JavaScript Exceptions!

Last but not least, sometimes we come up to a situation that we need to catch the global javascript exception that may occur for whatever reason could be. window.onerror is a good place to catch such exception.

I added a JavaScriptLoggingOptions which is shown below to make things configurable in the way that you want.

public class JavaScriptLoggingOptions
{
public bool HandleGlobalExceptions { get; set; }
}

By adding this simple property, the JavaScriptLoggingSnippet is now able to choose the proper script to render in the view.

public class JavaScriptLoggingSnippet
{
private readonly JavaScriptLoggingOptions _loggingOptions; private static readonly HtmlString JavaScriptLoggingScript = new HtmlString(Resources.Script); private static readonly HtmlString JavaScriptLoggingGlobalExceptionHandlingScript = new HtmlString(Resources.GlobalExceptionHandlingScript); public JavaScriptLoggingSnippet(IOptions<JavaScriptLoggingOptions> loggingOptions)
{
_loggingOptions = loggingOptions.Value;
} public HtmlString Script =>
_loggingOptions.HandleGlobalExceptions ? FullScript : JavaScriptLoggingScript; private static HtmlString FullScript => JavaScriptLoggingScript.Concat(HtmlString.NewLine,
JavaScriptLoggingGlobalExceptionHandlingScript);
}

What it takes to make everything happen?

We need few steps to make this happen:

First we need to configure the JavaScriptLogging service in the ConfigureServices method

services.AddJavaScriptLogging(options =>
{
options.HandleGlobalExceptions = true;
});

After that adding the JavaScriptLoggingMiddleware to the Configure method

app.UseJavaScriptLogging();

Finally add the following line into your view or layout page to render the jsLogger script.

@Html.Raw(JavaScriptLoggingSnippet.Script)

You can download the source code for this post from my jsLogger repository on GitHub.

集成Javascript Logging on MVC or Core的更多相关文章

  1. 国产化之路-统信UOS + Nginx + Asp.Net MVC + EF Core 3.1 + 达梦DM8实现简单增删改查操作

    专题目录 国产化之路-统信UOS操作系统安装 国产化之路-国产操作系统安装.net core 3.1 sdk 国产化之路-安装WEB服务器 国产化之路-安装达梦DM8数据库 国产化之路-统信UOS + ...

  2. 【干货理解】理解javascript中实现MVC的原理

    理解javascript中的MVC MVC模式是软件工程中一种软件架构模式,一般把软件模式分为三部分,模型(Model)+视图(View)+控制器(Controller); 模型:模型用于封装与应用程 ...

  3. javascript widget ui mvc

    MVC只是javascript的一个UI模式 JavaScript UI----UI, Template, MVC(View)----Backbone, Angular RequireJS------ ...

  4. 开源题材征集 + MVC&EF Core 完整教程小结

    到目前为止,我们的MVC+EF Core 完整教程的理论部分就全部结束了,共20篇,覆盖了核心的主要知识点. 下一阶段是实战部分,我们将会把这些知识点串联起来,用10篇(天)来完成一个开源项目. 现向 ...

  5. FineUIPro/Mvc/Core/JS v4.2.0 发布了(老牌ASP.NET控件库,WebForms,ASP.NET MVC,Core,JavaScript)!

    还记得 10 年前那个稍微青涩的 ExtAspNet 吗,如今她已脱胎换骨,变成了如下 4 款产品: FineUIPro:基于jQuery的经典款ASP.NET WebForms控件,之前的FineU ...

  6. 30行代码实现Javascript中的MVC

    从09年左右开始,MVC逐渐在前端领域大放异彩,并终于在刚刚过去的2015年随着React Native的推出而迎来大爆发:AngularJS.EmberJS.Backbone.ReactJS.Rio ...

  7. JavaScript富应用MVC MVVM框架

    对框架的挑选 Ember.js.Backbone.js.Knockout.js.Spine.js.Batman.js , Angular.js 1. 轻量级的应用选择哪一个会比较好?2. 那一个比较简 ...

  8. 改造继续之eclipse集成tomcat开发spring mvc项目配置一览

    在上一篇的环境配置中,你还只能基于maven开发一个javase的项目,本篇来看如果开发一个web项目,所以还得配置一下tomcat和spring mvc. 一:Tomcat安装 在.net web开 ...

  9. ASP.NET Core MVC+EF Core从开发到部署

    笔记本电脑装了双系统(Windows 10和Ubuntu16.04)快半年了,平时有时间就喜欢切换到Ubuntu系统下耍耍Linux,熟悉熟悉Linux命令.Shell脚本以及Linux下的各种应用的 ...

随机推荐

  1. 用 Django 管理现有数据库

    在多数项目中,总有一些几乎一成不变的 CRUD 操作,编写这些代码很无聊,但又是整个系统必不可少的功能之一.我们在上一个项目中也面临类似的问题,虽然已经实现了一个功能相对完整的管理后台,也尽量做到了代 ...

  2. 探究如何永久更改Maven的Dynamic Web Project版本及pom.xml默认配置

    一:问题 在用eclipse创建一个maven project (webApp)时,我们一般会要进行许多麻烦的配置,比如 1.更改Java jdk版本为1.7或1.8(默认1.5) 2.补全src/m ...

  3. zookeeper核心-zab协议-《每日五分钟搞定大数据》

    上篇文章<paxos与一致性>说到zab是在paxos的基础上做了重要的改造,解决了一系列的问题,这一篇我们就来说下这个zab. zab协议的全称是ZooKeeper Atomic Bro ...

  4. 《React Native 精解与实战》书籍连载「Node.js 简介与 React Native 开发环境配置」

    此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...

  5. 第八次oo作业

    作业五 作业五是当前最后一次电梯作业,也是我们第一次接触到多线程编程,输入方式也由之前的一次性输入变为了实时输入,其中涉及到大量的同步和冲突,其中学习多线程的使用也花了大量的时间,但总的来说为以后的作 ...

  6. poj3468 线段树的懒惰标记

    题目链接:poj3468 题意:给定一段数组,有两种操作,一种是给某段区间加c,另一种是查询一段区间的和 思路:暴力的方法是每次都给这段区间的点加c,查询也遍历一遍区间,复杂度是n*n,肯定过不去,另 ...

  7. Elasticsearch的DSL之比较重要的几个查询语句

    1.  match_all { "match_all": {}} 匹配所有的, 当不给查询条件时,默认. 2. match 进行full text search或者exact va ...

  8. 正则表达式验证input文本框

    方便以后的查找,直接copy代码在这里了. eg: //公司邮箱验证 if ($("#Email").val() != "") { var myreg = /^ ...

  9. (Git 学习)Git SSH Key 创建步骤

    首先感谢segmentfalut上的朋友对我帮助. 首先:查看你是否有../ssh 这个文件:怎么查看:找到你的git安装目录,在安装目录下查看是否./ssh,以我的为例: 在C盘/Users/11/ ...

  10. 福州大学软件工程1816 | W班 第10次作业[个人作业——软件产品案例分析]

    作业链接 个人作业--软件产品案例分析 评分细则 本次个人项目分数由两部分组成(课堂得分(老师/助教占比60%,学生占比40%)满分40分+博客分满分60分) 课堂得分和博客得分表 评分统计图 千帆竞 ...