自己写的Log记录组件

  常规的Debug组件的封装,然后加了一个文件log,分异步和同步(可跨平台使用)。

/// <summary>
    /// 常用IO操作类
    /// </summary>
    public class HIO
    {
        /// <summary>
        /// 控制台数据错误
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteConsole(Exception ex)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine("Data:" + ex.Data + Environment.NewLine
            + " InnerException:" + ex.InnerException + Environment.NewLine
            + " Message:" + ex.Message + Environment.NewLine
            + " Source:" + ex.Source + Environment.NewLine
            + " StackTrace:" + ex.StackTrace + Environment.NewLine
            + " TargetSite:" + ex.TargetSite);
        }
        /// <summary>
        /// 控制台数据错误
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteDebug(Exception ex)
        {
            Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            Debug.WriteLine("Data:" + ex.Data + Environment.NewLine
            + " InnerException:" + ex.InnerException + Environment.NewLine
            + " Message:" + ex.Message + Environment.NewLine
            + " Source:" + ex.Source + Environment.NewLine
            + " StackTrace:" + ex.StackTrace + Environment.NewLine
            + " TargetSite:" + ex.TargetSite);
        }
        /// <summary>
        /// 应用根目录
        /// </summary>
        public static string AppRootPath = AppDomain.CurrentDomain.BaseDirectory;// Environment.CurrentDirectory
        /// <summary>
        /// 日志目录
        /// </summary>
        public static string logDir = "Log";
        /// <summary>
        /// 日志目录全路径
        /// </summary>
        public static string logDirPath = AppRootPath + Path.DirectorySeparatorChar + logDir;
        /// <summary>
        /// 错误记录
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteLog(Exception ex)
        {
            WriteLog("Data:" + ex.Data + Environment.NewLine
                + " InnerException:" + ex.InnerException + Environment.NewLine
                + " Message:" + ex.Message + Environment.NewLine
                + " Source:" + ex.Source + Environment.NewLine
                + " StackTrace:" + ex.StackTrace + Environment.NewLine
                + " TargetSite:" + ex.TargetSite);
        }
        /// <summary>
        /// 写log
        /// </summary>
        /// <param name="InfoStr"></param>
        public static void WriteLog(string info)
        {
            WriteLog(info, logDirPath);
        }
        /// <summary>
        /// 写log(自动时间log)
        /// </summary>
        /// <param name="InfoStr">内容</param>
        /// <param name="FilePath">目录地址</param>
        public static void WriteLog(string info, string DirPath)
        {
            FileStream stream = null;
            System.IO.StreamWriter writer = null;
            try
            {
                if (Directory.Exists(DirPath) == false)
                {
                    Directory.CreateDirectory(DirPath);
                }
                string dateDir = DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(DirPath + Path.DirectorySeparatorChar + dateDir)) { Directory.CreateDirectory(DirPath + Path.DirectorySeparatorChar + dateDir); }
                string logFilePath = DirPath + Path.DirectorySeparatorChar + dateDir
                    + Path.DirectorySeparatorChar + "SyncLog_" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
                if (File.Exists(logFilePath) == false)
                {
                    stream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                }
                else
                {
                    stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }
                writer = new System.IO.StreamWriter(stream);
                writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                writer.WriteLine(info);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
        /// <summary>
        /// 异步写log
        /// </summary>
        /// <param name="info"></param>
        public static void AsyncWriteLog(string info)
        {
            AsyncWriteLog(info, Encoding.UTF8, logDirPath);
        }
        /// <summary>
        /// 异步写log
        /// </summary>
        /// <param name="ex"></param>
        public static void AsyncWriteLog(Exception ex)
        {
            AsyncWriteLog("Data:" + ex.Data + Environment.NewLine
                + " InnerException:" + ex.InnerException + Environment.NewLine
                + " Message:" + ex.Message + Environment.NewLine
                + " Source:" + ex.Source + Environment.NewLine
                + " StackTrace:" + ex.StackTrace + Environment.NewLine
                + " TargetSite:" + ex.TargetSite, Encoding.UTF8, logDirPath);
        }
        /// <summary>
        /// 异步写log
        /// </summary>
        /// <param name="info"></param>
        /// <param name="encode"></param>
        /// <param name="FilePath"></param>
        public static void AsyncWriteLog(string info, Encoding encode, string FileDirPath)
        {
            AsyncWriteLog(encode.GetBytes(info), FileDirPath);
        }
        /// <summary>
        /// 异步写log
        /// </summary>
        /// <param name="datagram">要写入当前流的数据的缓冲区</param>
        /// <param name="FilePath"></param>
        public static void AsyncWriteLog(byte[] datagram, string FileDirPath)
        {
            AsyncWriteLog(datagram, datagram.Length, FileDirPath, (obj) =>
            {
                AsyncResult ar = obj as AsyncResult;
                FileStream stream = ar.AsyncState as FileStream;
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            });
        }
        /// <summary>
        /// 异步写log
        /// </summary>
        /// <param name="datagram">要写入当前流的数据的缓冲区</param>
        /// <param name="numBytes">最多写入的字节数</param>
        /// <param name="FilePath"></param>
        /// <param name="callback"></param>
        public static void AsyncWriteLog(byte[] datagram, int numBytes, string FileDirPath, AsyncCallback callback)
        {
            if (datagram.Length == 0) { throw new Exception("数据为0"); }
            if (numBytes == 0) { throw new Exception("写入数为0"); }
            if (string.IsNullOrEmpty(FileDirPath)) { throw new Exception("文件地址为空"); }
            if (!Directory.Exists(FileDirPath)) { Directory.CreateDirectory(FileDirPath); }
            string dateDir = DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(FileDirPath + Path.DirectorySeparatorChar + dateDir)) { Directory.CreateDirectory(FileDirPath + Path.DirectorySeparatorChar + dateDir); }
            string logFilePath = FileDirPath + Path.DirectorySeparatorChar + dateDir
                + Path.DirectorySeparatorChar + "AsyncLog_" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
            FileStream stream = null;
            try
            {
                if (File.Exists(logFilePath) == false)
                {
                    stream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                }
                else
                {
                    stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }

                if (stream.CanWrite)
                {
                    stream.BeginWrite(datagram, 0, numBytes, callback, stream);
                }
                else
                {
                    throw new Exception("文件无法写入,文件或只读!");
                }
            }
            catch (Exception ex)
            {
                WriteDebug(ex);
            }
        }
        /// <summary>
        /// 文本转义(方便讲文本转换成C#变量代码)
        /// 例子 " 转化成 string str="\"";
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToEscape(string str, string m_var)
        {
            /*
                "           \"
                \           \            */
            str = str.Trim();
            str = str.Replace("\\", "\\\\");
            str = str.Replace("\"", "\\\"");
            return "string " + m_var + "=\"" + str + "\";";
        }

        /// <summary>
        /// (递归)去掉所有首部出现的字符串
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="headStr">首部出现的字符串</param>
        /// <returns></returns>
        public static string RemoveHead(string str, string headStr)
        {
            if (str.StartsWith(headStr))
            {
                str = str.Remove(0, headStr.Length);
                return RemoveHead(str, headStr);
            }
            else
            {
                return str;
            }
        }
        /// <summary>
        /// 路径解析转换,转化成符合当前系统的路径符号
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="flag">(路径的类型)1:windows \ 2:linux /(linux和web网页的分隔相符)</param>
        /// <param name="dHear">是否去掉首部的路径分隔符</param>
        /// <returns></returns>
        public static string PathParse(string path, int flag, bool dHear)
        {
            string win = @"\";
            string linux = @"/";
            string sys = Path.DirectorySeparatorChar.ToString();
            if (flag == 1)
            {
                path = path.Replace(win, sys);
            }
            else if (flag == 2)
            {
                path = path.Replace(linux, sys);
            }
            if (dHear)
            {
                path = RemoveHead(path, sys);
            }
            return path;
        }
        /// <summary>
        /// web路径地址转换为系统路径
        /// </summary>
        /// <param name="appPath">应用路径</param>
        /// <param name="webPath">web路径</param>
        /// <param name="dHear">是否去掉首部的路径分隔符</param>
        /// <returns></returns>
        public static string SysPathParse(string appPath, string webPath, bool dHear)
        {
            string sys = Path.DirectorySeparatorChar.ToString();
            string web = @"/";//web的分隔符
            webPath = webPath.Replace(web, sys);
            if (dHear)
            {
                webPath = RemoveHead(webPath, sys);
            }
            string result = "";
            if (appPath.EndsWith(sys))
            {
                if (webPath.StartsWith(sys))
                {
                    result = appPath + webPath.Remove(0, 1);
                }
                else
                {
                    result = appPath + webPath;
                }
            }
            else
            {
                if (webPath.StartsWith(sys))
                {
                    result = appPath + webPath;
                }
                else
                {
                    result = appPath + sys + webPath;
                }
            }
            return result;
        }
        public static string WebPathParse(string fullPath, string appPath, bool dHear)
        {
            string sys = Path.DirectorySeparatorChar.ToString();
            string web = @"/";//web的分隔符
            if (fullPath.StartsWith(appPath))
            {
                string webPath = fullPath.Remove(0, appPath.Length);
                webPath = webPath.Replace(sys, web);
                if (webPath.StartsWith(web) == false)
                {
                    webPath = web + webPath;
                }
                if (dHear)
                {
                    webPath = RemoveHead(webPath, web);
                }
                return webPath;
            }
            else
            {
                return "";
            }
        }
    }

  

时间: 2024-12-15 01:53:46

自己写的Log记录组件的相关文章

C#Log4net日志记录组件的使用

一.Log4Net介绍 Log4net是基于.NET开发的一款非常著名的记录日志开源组件.它通过一套XML配置的日志引擎,将日志分不同的等级,分别是:FATAL . ERROR. WARN. INFO . DEBUG.ALL(允许所有的日志请求)和OFF(拒绝所有的日志请求),缺省为DEBUG,前五个可以看到和我们平常在调试应用程序的出错有点类似,在编译器中也会留下如错误.警告之类的提示信息,它们的错误级别不断的降低. 我们接着看Log4net的核心组成部分,Log4net主要由五个部分组成,分

Elmah 日志记录组件

[http://www.cnblogs.com/chenkai/archive/2013/01/26/2877855.html] 常在服务器端处理用户请求时.特别是针对Web应用程序.当出现异常是可以根据日志操作记录还原异常出现时操作步骤.而记录异常堆栈信息判断问题出现问题位置. 为了跟踪和记录服务器行为.特别是针对出现异常时构建简单.统一的异常处理模式就显得尤为重要. 如果有一个基础的架构用来记录服务器端中日志和事件.那么对于调试和在问题的解决就变得更加简单直接.针对日志记录.可能针对大部分开

C# 程序A发送Log记录给程序B,程序B处理和分析Log记录

关键字:C# ;Log记录 ;在线Log记录;Socket:httplistener 一.常用场景 1. APP开发,在真机或者虚拟机上面运行由H5或者ApiCloud的程序,或者调试别人写的程序的时候,往往不能看到一段代码执行后的输出结果是什么.作为一个天天跟后台打交道的人,浏览器尤其是习惯了Google的F12的console.log,更是希望APP调试也能够实时查看输出. 2.开发一个.Net的网站,或者Java的网站,在调试的时候,写了很多的System.console.writelin

cocos2d-js 写日志log 查看日志log Android调试查看log

1 输出日志的方式,当然是cc.log了 2 如何查看日志?        a)如果小程序可以先在浏览器上跑,例如用chrome,在控制台就可以看到输出的log:        b)如果在真机上调试,就需要用log工具了.Android上使用logcat.   3 Android调试使用logcat的办法 logcat位置:Android SDK目录中 D:\AndroidDevelopTools\sdk\platform-tools 查看步骤: 连接手机 cmd方式打开logcat:adb.e

以HTML为表现的日志记录组件

关于日志记录,如果你不想随用随写,又不想用log4net的话,也许你可以了解一下这个! 我也是个很懒的人,程序上的东西,只要别人写好了,而且自己用着爽,绝不做重复的coding.这个组件的起源是因为感觉log4net太强大太复杂(对我来说真是这样),当我想用log4net的时候,看到配置我都吓尿n次了,而这个时候心中又突发奇想,用HTML来做日志的表现!理由有二,一是HTML和CSS大家都会,二是可以实现很好的可读可视性. 一.配置文件说明 <?xml version="1.0"

小玩意--自定义log记录

之前在帮TCL运维项目时,因某些原因,决定单就经销商相关业务中摒弃经典的log4j日志,改为每日自定义生成并写入相关日志,我遂写了一个util,代码如下:p.s.实现的思路很简单,仅为每次需要记录时,调取util中方法,若当日的日志文件不存在,则创建,存在,则追加log内容. package com.aebiz.b2b2c.baseframework.utils; import java.io.File; import java.io.FileWriter; import java.io.IOE

MVC使用 Elmah 日志记录组件

简介 ELMAH(Error Logging Modules and Handlers)错误日志记录模块和处理程序,是一种应用广泛的错误日志工具是完全可插拔.它可以动态添加到一个正在运行的ASP.NET Web应用程序,甚至是一台机器上的所有ASP.NET Web应用程序,而无需重新编译或重新部署. ELMAH既支持ASP.NET Web Forms 又支持 ASP.NET MVC.你可以对ELMAH进行配置来存储各种不同的错误(XML文件,事件日志,Access数据库,SQL数据库,Oracl

deirective写form表单组件

directive 在使用隔离 scope 的时候,提供了三种方法同隔离之外的地方交互.这三种分别是 @ 绑定一个局部 scope 属性到当前 dom 节点的属性值.结果总是一个字符串,因为 dom 属性是字符串.& 提供一种方式执行一个表达式在父 scope 的上下文中.如果没有指定 attr 名称,则属性名称为相同的本地名称.= 通过 directive 的 attr 属性的值在局部 scope 的属性和父 scope 属性名之间建立双向绑定 但是当我们不使用隔离scope的时候,我们要能够

利用React写一个评论区组件(React初探)

本文是在阅读学习了官方的React Tutorial之后的整理,实例链接. 开始使用React 首先从官方获取React.js的最新版本(v0.12.2),或者下载官方的Starter Kit,并在我们的html中引入它们: <head> <meta charset="UTF-8"> <title>React Test Page</title> <script src="../build/react.js">