为App添加Log日志文件
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms; namespace app.Lib
{
public enum Level
{
Debug,
Exception,
Info,
Warn,
} public enum Priority
{
None,
High,
Medium,
Low,
}
public class Logger
{
private static StreamWriter _writer;
//private static string _format = "{1}: {2}. Priority: {3}. Timestamp:{0:u}";
private static string _format = "{0:u}:{1:D3} {2}: {3}";
private static StreamWriter Writer
{
get
{
if (_writer == null)
{
string path = Application.StartupPath + "//Log//" + DateTime.Now.ToString("yyyy") + "//" +
DateTime.Now.ToString("yyyyMM") + "//" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
string filepath = Application.StartupPath + "//Log//" + "//bmp//"; string dir = Path.GetDirectoryName(path);
string filedir = Path.GetDirectoryName(filepath); if (filedir != null && !Directory.Exists(filedir))
{
Directory.CreateDirectory(filedir);
} if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
_writer = new StreamWriter(path, true, Encoding.Default);
_writer.AutoFlush = true;
}
return _writer;
}
} public static string GetFileDirName()
{
return Application.StartupPath + "//Log" + "//bmp//";
} public static void Log(string message, Level level)
{
string messageToLog = String.Format(CultureInfo.InvariantCulture, _format, DateTime.Now, DateTime.Now.Millisecond,
level.ToString().ToUpper(CultureInfo.InvariantCulture), message); Writer.WriteLine(messageToLog);
} public static bool EnableLog;
}
}
很多时候需要为我们应用程序添加日子文件,方便问题定位
代码转载而来,非原创
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection; namespace CommonLib
{
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
All,
Information,
Debug,
Success,
Failure,
Warning,
Error
} public class Logger
{ #region Instance
private static object logLock; private static Logger _instance; private static string logFileName;
private Logger() { } /// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
//logFileName = Guid.NewGuid() + ".log";
logFileName = DateTime.Now.Hour.ToString("") + DateTime.Now.Minute.ToString("") +DateTime.Now.Second.ToString("") + ".log";
}
return _instance;
}
}
#endregion /// <summary>
/// Write log to log file
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">Log type</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
if (!Directory.Exists(basePath + "\\Log"))
{
Directory.CreateDirectory(basePath + "\\Log");
} string dataString = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + "\\Log\\" + dataString))
{
Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
} string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
//fileName = DateTime.Now.ToString("hh:mm:ss");
} lock (logLock)
{
File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
}
}
catch (Exception) { }
} /// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
} }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection; namespace CommonLib
{
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
All,
Information,
Debug,
Success,
Failure,
Warning,
Error
} public class Logger
{ #region Instance
private static object logLock; private static Logger _instance; private static string logFileName;
private Logger() { } /// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
//logFileName = Guid.NewGuid() + ".log";
logFileName = DateTime.Now.Hour.ToString("") + DateTime.Now.Minute.ToString("") +DateTime.Now.Second.ToString("") + ".log";
}
return _instance;
}
}
#endregion /// <summary>
/// Write log to log file
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">Log type</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
if (!Directory.Exists(basePath + "\\Log"))
{
Directory.CreateDirectory(basePath + "\\Log");
} string dataString = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + "\\Log\\" + dataString))
{
Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
} string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
//fileName = DateTime.Now.ToString("hh:mm:ss");
} lock (logLock)
{
File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
}
}
catch (Exception) { }
} /// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
} }
}
为App添加Log日志文件的更多相关文章
- 使用触发器实现记录oracle用户登录失败信息到alert.log日志文件
前面我们说了用oracle自带的审计功能可以实现记录用户登录失败日志到数据表中(链接:http://www.54ok.cn/6778.html).今天我们来分享一下如何把用户登录失败信息记录到aler ...
- log4j.properties配置与将异常输出到Log日志文件实例
将异常输出到 log日志文件 实际项目中的使用: <dependencies> <dependency> <groupId>org.slf4j</groupI ...
- Linux系统的LOG日志文件及入侵后日志的清除
UNIX网管员主要是靠系统的LOG,来获得入侵的痕迹.当然也有第三方工具记录入侵系统的 痕迹,UNIX系统存放LOG文件,普通位置如下: /usr/adm - 早期版本的UNIX/var/adm - ...
- Android APP测试的日志文件抓取
1 log文件分类简介 实时打印的主要有:logcat main,logcat radio,logcat events,tcpdump,还有高通平台的还会有QXDM日志 状态信息的有: ...
- Android中对Log日志文件的分析[转]
一,Bug出现了, 需要“干掉”它 bug一听挺吓人的,但是只要你懂了,android里的bug是很好解决的,因为android里提供了LOG机制,具体的底层代码,以后在来分析,只要你会看bug, a ...
- C#中添加log4net(日志文件)
1.先下载引用“log4net” 2.然后再App.config配置 3.添加一个LogHandler类 4.在Assemblyinfo类中添加配置的读取文件 5.运用日志文件 6.显示结果
- 关于pptpd log日志文件的配置
如何开启pptpd默认日志记录功能. 修改/etc/ppp/options.pptpd中的nologfd,默认没有开,把nologfd注释掉,然后添加 logfile /var/log/pptpd.l ...
- 怎样在idea添加log日志 以及log4j2配置文件解读
网上找了很多篇文章,就数这篇比较全,从下载到配置都有讲到,解决从0开始接触java日志文件添加的各位同学.参考文章:https://www.cnblogs.com/hong-fithing/p/769 ...
- 解决Linux下Tomcat日志目录下的catalina.log日志文件过大的问题
本文摘自:(http://blog.csdn.net/stevencn76/article/details/6246162) 分类: Java技术专区2011-03-13 12:25 5017人阅读 ...
随机推荐
- Python3+unitest自动化测试初探(中篇)
目录 6.生成测试报告 7.编写邮件发送工具 8.发送邮件 发布 0 86 编辑 删除 Python3+unitest自动化测试初探(中篇)(2019-04-18 01:41) 发布 3 245 编辑 ...
- linux 指令备忘
linux 指令备忘 1.ls [选项] [目录名 | 列出相关目录下的所有目录和文件 -a 列出包括.a开头的隐藏文件的所有文件 -A 通-a,但不列出"."和"..& ...
- 程序猿想聊天 - 創問 4C 團隊教練心得(一)
今天難得參加了創問舉辦的 4C 團隊教練課程 From : http://www.cccoach.cn/Home/Activity/show/id/449.html 整個課程主要圍繞著 Common ...
- c# 构造tree下拉框,空格转化
c#代码写的空格如何在html中的select中展示出来呢? var str = ""; //父级菜单不缩进 ; j < i; j++) { str += HttpUtili ...
- FreeMarker js 获取后台设置的request、session
使用Request里的Attribute值最简单的方法就是直接${AttributeName}或者安全一点:${AttributeName!"default Value"} 1.取 ...
- 2014年第五届蓝桥杯javaB组 试题 答案 解析
1.武功秘籍 小明到X山洞探险,捡到一本有破损的武功秘籍(2000多页!当然是伪造的).他注意到:书的第10页和第11页在同一张纸上,但第11页和第12页不在同一张纸上. 小明只想练习该书的第81页到 ...
- 原生jQuery代码
function myJquery(selector){ if(typeof selector=="string") { if (selector.charAt(0) == &qu ...
- Hacking HackDay: Albania
概述: Name: HackDay: Albania Date release: 18 Nov 2016 Author: R-73eN Series: HackDay 下载: https://down ...
- java 设计模式 ---- 单例模式
只产生一个实例, 所以要使用静态方法对外暴露对象(如果使用反射技术, 也能调用私有的构造方法) 懒汉模式 并发时还是可能会产生多个实例, 所以同步处理 public class User{ priva ...
- 商米D1S一体机设置搜狗手写输入法图解
按照下图步骤,一步步设置即可,询问全新的时候需要点击允许. 商米应用市场搜索下载搜狗输入法,并安装 安装完成后,点击桌面搜狗输入法,选择启用搜狗输入法,如图 点击启用后,在虚拟键盘中选择搜狗输入法,并 ...