以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 |
| 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#代码的日志辅助类,供参考:
usingNewtonsoft.Json;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceDemo{classLogHelper{publicstaticasyncTask<bool>WriteInfo(stringmsg,objectextensionData=null){boolflag=false;stringlogMessage=msg;stringattData="";if(extensionData!=null){try{attData=JsonConvert.SerializeObject(extensionData);}catch(Exceptione){}}flag=awaitAddLog("Info",logMessage,attData,null);returnflag;}publicstaticasyncTask<bool>WriteError(stringmsg,Exceptionex,objectextensionData=null){boolflag=false;stringlogMessage=msg+":"+ex.Message;stringstackInfo=ex.StackTrace;stringattData="";if(extensionData!=null){try{attData=JsonConvert.SerializeObject(extensionData);}catch(Exceptione){}}flag=awaitAddLog("Error",logMessage,attData,stackInfo);returnflag;}privatestaticasyncTask<bool>AddLog(stringlogLevel,stringlogMessage,stringattData,stringstackInfo){boolflag=false;try{Dictionary<string,object>dicArgs=newDictionary<string,object>();dicArgs.Add("systemId",SystemConfig.config.LogSystemId);dicArgs.Add("logLevel",logLevel);dicArgs.Add("logMessage",logMessage);dicArgs.Add("attData",attData);dicArgs.Add("stackInfo",stackInfo);varres=awaitNetHelper.Request(SystemConfig.config.LogUrl,dicArgs,"POST");OPResultopRes=JsonConvert.DeserializeObject<OPResult>(res);if(opRes.State==1){flag=true;}else{Console.WriteLine("调用日志系统失败:"+res);}}catch(Exceptionex){Console.WriteLine("调用日志系统失败:"+ex.Message,ex);}returnflag;}privateclassOPResult{publicintState{get;set;}publicobjectData{get;set;}}}}NetHelper:
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Web;namespaceDemo{publicclassNetHelper{/// <summary>/// 发起一次请求--不记录和回传sessionID的/// </summary>/// <param name="url">请求的URL</param>/// <param name="paraDic">请求的参数集合</param>/// <param name="requestType">请求方式</param>/// <returns></returns>publicstaticasyncTask<string>Request(stringurl,Dictionary<string,object>paraDic,stringrequestType,stringcontentType="application/x-www-form-urlencoded;charset=UTF-8;",stringaccept="",WebHeaderCollectionrequestHeaderCollection=null){try{Uriuri=newUri(url);HttpWebRequestrequest=(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&¶Dic.Count>0){StringBuildersbParams=newStringBuilder();foreach(stringiteminparaDic.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;StreamreqStream=awaitrequest.GetRequestStreamAsync();reqStream.Write(reqBytes,0,reqBytes.Length);}WebResponseresponse=awaitrequest.GetResponseAsync();Streamstream=response.GetResponseStream();StreamReadersr=newStreamReader(stream);stringstr=sr.ReadToEnd();response.Close();returnstr;}catch(Exceptionex){varextenData=new{Url=url,Args=paraDic};//LogHelper.WriteError("发送HTTP请求时发生异常:" + ex.Message, ex, extenData);Console.WriteLine("发送HTTP请求时发生异常:"+ex.Message);returnJsonConvert.SerializeObject(new{State=0,Data=ex.Message});}}}}下边附上PostMan的调用参数与返回值截图:
日志查询
查询所有业务系统的日志,访问http://localhost:81/ui/pages/sysloglist.aspx
查询指定业务系统的日志,访问http://localhost:81/ui/pages/log.aspx?systemId=xxx
最后祝大家使用愉快,如果有帮助到您,记得点个星,再见不负遇见!
