Giter Club home page Giter Club logo

logservice's Introduction

日志服务

以WebApi和Web页面的方式提供通用的日志记录与查询服务(基于.NetFramework4.5,写于2015年)




部署说明

在mysql数据库上运行database.sql,以创建库表结构.


用VS打开LogSystem.sln解决方案,右击LogSystem项目选择发布,将程序发布到您磁盘的某目录下,修改web.config中的数据库链接字符串,以及log4net配置部分的MariaDBAppender的数据库连接字符串(用于记录系统本身的日志).

在IIS(IIS7)以上新建一个网站(而不是添加应用程序),指向发布目录,应用程序池选择NetFramework4.0版本.
为该网站添加以下2个MIME类型以正确显示字体图标:

.woff application/x-font-woff

.woff2 application/x-font-woff


接口说明

接口名称
接口地址
参数说明
请求方式
返回值
备注
写入日志API/AddLog
参数名
参数类型
备注
systemIdstring业务系统的ID,每个业务系统一个固定的ID,由接入时分配
logLevelstring日志级别
logMessagestring日志标题,如 "支付时产生异常:网络不通"
attDatastring可选,记录日志时附加的业务数据,要求json格式
stackInfostring可选,堆栈信息,
POST{     "State":1,     "Data":null}

State为1时代表成功,Data为null,

State为其它时,Data为具体失败的原因


使用方式

日志记录

记录前的准备:

1,请先在biz_system表里添加业务系统的信息,id字段就是业务系统的systemId,一般用guid.

2,重启网站(目的是刷新缓存中的业务系统信息))或用PostMan调用ApiController中的RefreshSystemList方法,该方法参数的systemId是Set.config中配置的,不是数据库中的.


记录日志:

如果您使用了Sunny框架,只要修改appsetting.json中的日志配置部分即可.



如果您没用使用Sunny框架,那么需要在程序中通过Post的方式调用ApiController中的AddLog方法.

下面是C#代码的日志辅助类,供参考:

using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Demo
{
    class LogHelper
    {
 
        public static async Task<bool> WriteInfo(string msg, object extensionData = null)
        {
            bool flag = false;
 
            string logMessage = msg;
            string attData = "";
 
            if (extensionData != null) {
                try {
                    attData = JsonConvert.SerializeObject(extensionData);
                }
                catch (Exception e) {
 
                }
            }
 
            flag = await AddLog("Info", logMessage, attData, null);
 
            return flag;
 
        }
 
        public static async Task<bool> WriteError(string msg, Exception ex, object extensionData = null)
        {
            bool flag = false;
 
            string logMessage = msg + ":" + ex.Message;
            string stackInfo = ex.StackTrace;
            string attData = "";
 
            if (extensionData != null) {
                try {
                    attData = JsonConvert.SerializeObject(extensionData);
                }
                catch (Exception e) {
 
                }
            }
 
            flag = await AddLog("Error", logMessage, attData, stackInfo);
 
            return flag;
        }
 
 
        private static async Task<bool> AddLog(string logLevel, string logMessage, string attData, string stackInfo)
        {
            bool flag = false;
 
            try {
 
                Dictionary<string, object> dicArgs = new Dictionary<string, object>();
 
                dicArgs.Add("systemId", SystemConfig.config.LogSystemId);
                dicArgs.Add("logLevel", logLevel);
                dicArgs.Add("logMessage", logMessage);
                dicArgs.Add("attData", attData);
                dicArgs.Add("stackInfo", stackInfo);
 
                var res = await NetHelper.Request(SystemConfig.config.LogUrl, dicArgs, "POST");
                OPResult opRes = JsonConvert.DeserializeObject<OPResult>(res);
                if (opRes.State == 1) {
                    flag = true;
                }
                else {
                    Console.WriteLine("调用日志系统失败:" + res);
                }
            }
            catch (Exception ex) {
                Console.WriteLine("调用日志系统失败:" + ex.Message, ex);
            }
 
            return flag;
 
        }
 
 
        private class OPResult
        {
            public int State { get; set; }
 
            public object Data { get; set; }
 
        }
 
    }
}

NetHelper:

using System;

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
 
namespace Demo
{
    public class NetHelper
    {
        /// <summary>
        /// 发起一次请求--不记录和回传sessionID的
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="paraDic">请求的参数集合</param>
        /// <param name="requestType">请求方式</param>
        /// <returns></returns>
        public static async Task<string> Request(string url, Dictionary<string, object> paraDic, string requestType, string contentType = "application/x-www-form-urlencoded;charset=UTF-8;", string accept = "", WebHeaderCollection requestHeaderCollection = null)
        {
            try {
                Uri uri = new Uri(url);
 
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                if (requestHeaderCollection != null) {
                    request.Headers = requestHeaderCollection;
                }
 
                request.ContentType = contentType;
                request.Accept = accept;
                request.Method = requestType.ToString();
                request.ContentLength = 0;
                request.Timeout = 1000 * 20;
 
                if (paraDic != null && paraDic.Count > 0) {
                    StringBuilder sbParams = new StringBuilder();
                    foreach (string item in paraDic.Keys) {
                        if (paraDic[item] != null) {
                            sbParams.Append("&" + item + "=" + HttpUtility.UrlEncode(paraDic[item].ToString()));
                        }
 
                    }
                    sbParams.Remove(0, 1);
 
                    byte[] reqBytes = Encoding.UTF8.GetBytes(sbParams.ToString());
                    request.ContentLength = reqBytes.Length;
                    Stream reqStream = await request.GetRequestStreamAsync();
                    reqStream.Write(reqBytes, 0, reqBytes.Length);
                }
 
                WebResponse response = await request.GetResponseAsync();
                Stream stream = response.GetResponseStream();
                StreamReader sr = new StreamReader(stream);
                string str = sr.ReadToEnd();
                response.Close();
                return str;
            }
            catch (Exception ex) {
                var extenData = new { Url = url, Args = paraDic };
                //LogHelper.WriteError("发送HTTP请求时发生异常:" + ex.Message, ex, extenData);
                Console.WriteLine("发送HTTP请求时发生异常:" + ex.Message);
                return JsonConvert.SerializeObject(new { State = 0, Data = ex.Message });
            }
        }
    }
}

下边附上PostMan的调用参数与返回值截图:

日志查询

查询所有业务系统的日志,访问http://localhost:81/ui/pages/sysloglist.aspx

查询指定业务系统的日志,访问http://localhost:81/ui/pages/log.aspx?systemId=xxx



最后祝大家使用愉快,如果有帮助到您,记得点个星,再见不负遇见!

logservice's People

Contributors

mackyang avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.