为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人阅读 ...
随机推荐
- 【java线程池】
一.概述 1.线程池的优点 ①降低系统资源消耗,通过重用已存在的线程,降低线程创建和销毁造成的消耗: ②提高系统响应速度,当有任务到达时,无需等待新线程的创建便能立即执行: ③方便线程并发数的管控,线 ...
- lib和dll文件的初了解
lib,dll这两样东西在许多编程书中都很少出现,但实际工程中,这两样东西的作用确实非常重要,我觉得c++程序员都有必要了解这两样东西. 首先总共有 动态链接 和 静态链接 这两种链接方式 |静态链接 ...
- Lumen框架—升级改造之路-开篇
一.前言 首先,我先阐述下,为什么要做这件事.lumen是一款比较轻型的PHP框架,但是,作为项目开发来说,它还是缺少很多东西,比如Response返回值规范的自定义,异常抛出格式的自定义,以及 ...
- [C#] C# 与 Nessus 交互,动态构建扫描任务计划
C# 与 Nessus 交互,动态构建扫描任务计划 目录 什么是 Nessus? 创建会话类 NessusSession 登录测试 创建操作类 NessusManager 操作测试 什么是 Nessu ...
- c#实战开发:以太坊钱包快速同步区块和钱包卡死解决方案 (三)
首先以太坊默认的快速同步模式 我们需要先设置当前同步模式内存大小512-2048范围 在服务器配置情况下最大化内存 输入以下命令 geth --fast --cache=2048 最快同步模式也是 保 ...
- 变量类型、构造器、封装以及 LeetCode 每日一题
1.成员变量和局部变量 1.1成员变量和局部变量定义 成员变量指的是类里面定义的变量(field),局部变量指的是在方法里定义的变量. 成员变量无须显示初始化,系统会自动在准备阶段或创建该类的实例时进 ...
- Django之CSRF跨站请求伪造(老掉牙的钓鱼网站模拟)
首先这是一个测试的代码 请先在setting页面进行下面操作 注释完成后,开始模拟钓鱼网站的跨站请求伪造操作: 前端代码: <!DOCTYPE html> <html lang=&q ...
- 虚拟机安装CentOS7(一)
软件环境 虚拟机:VMware Workstation Linux:CentOS-7-x86_64-DVD-1708.iso镜像文件 虚拟机所在电脑系统:win7 安装步骤 安装VMware 下载Li ...
- Nginx Windows详细安装部署教程
一.Nginx简介 Nginx (engine x) 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器.Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Ramble ...
- 【AO笔记】关于创建IFeatureClass中的参考系设置——不能为null也不能为IUnknownCoodinateSystem
创建一个要素类是很简单的,只需要获取一枚IFeatureWorkspace或者一个IFeatureDataset,然后调用其CreateFeatureClass()即可. 这个CreateFeatur ...