log4js日志

安装log4js:npm install log4js

express中配置log4js中间件:

var log = require("./modules/utils/logUtil.js");
log.use(app);

logUtil工具类:

/**
 * Created by Administrator on 2015/9/8.
 */
"use strict";

var helper = {};
var log4js = require('log4js');
var fs = require("fs");
var path = require("path");
var dbOperate = require("./dbUtil.js");
helper.levels = {
    FATAL: log4js.levels.FATAL,
    ERROR: log4js.levels.ERROR,
    WARN: log4js.levels.WARN,
    DEBUG: log4js.levels.DEBUG,
    INFO: log4js.levels.INFO
};
helper.config =
{
    "appenders": [
        {
            "type": "console",
            "category": "console"
        },
        {
            "filename": "logs/",
            "pattern": "yyyyMMdd.log",
            "category": "logInfo",
            "type": "dateFile",
            "alwaysIncludePattern": true,
            "level":"INFO"
        }
    ],
    "replaceConsole": true
};

// 加载配置文件
//var objConfig = JSON.parse(fs.readFileSync(path.join(__dirname + "/config"), "utf8"));
log4js.configure(helper.config);
var logInfo = log4js.getLogger('logInfo');
var name = null;

/**
 * 日志保存
 * @param req   request请求,用于获取ip、url等信息
 * @param operateType   操作类型,例如:0000-登录,1111-退出
 * @param operateData   被操作的数据
 * @param category  日志类别(日志模块类别)
 * @param results   操作结果
 * @param msg   log信息
 * @param logLevel     日志level:详见helper.levels
 */
helper.saveLogFile = function (req, operateType,operateData, category, results, msg, logLevel) {
    var logLevel = logLevel.toString();
    var conf =
    {
        "appenders": [
            {
                "type": "console",
                "category": "console"
            },
            {
                "filename": "logs/",
                "pattern": "yyyyMMdd.log",
                "category": category,
                "type": "dateFile",
                "alwaysIncludePattern": true,
                "level":logLevel
            }
        ],
        "replaceConsole": true
    };
    log4js.configure(conf);
    name = log4js.getLogger(category);
    if (msg == null)
        msg = "";
    var username;
    if(typeof req.session.user != "undefined"){
        username = req.session.user.username;
    }else{
        username = req.body.username;
    }
    switch (logLevel) {
        case 'ERROR':
            name.error("msg:" + msg +  "user:" + username + "ip:" + req.ip + " url:" + req.originalUrl + " operateType:" + operateType +  " operateData:"
                + operateData + " results:" + results + " User-Agent:" + req.get("User-Agent"));
            break;
        case 'WARN':
            name.warn("msg:" + msg + " user:" + username + " ip:" + req.ip + " url:" + req.originalUrl + " operateType:" + operateType + " operateData:"
                + operateData + " results:" + results + " User-Agent:" + req.get("User-Agent"));
            break;
        case 'DEBUG':
            name.debug("msg:" + msg + " user:" + username + " ip:" + req.ip + " url:" + req.originalUrl + " operateType:" + operateType + " operateData:"
                + operateData + " results:" + results + " User-Agent:" + req.get("User-Agent"));
            break;
        case 'FATAL':
            name.fatal("msg:" + msg + " user:" + username + " ip:" + req.ip + " url:" + req.originalUrl + " operateType:" + operateType + " operateData:"
                + operateData + " results:" + results + " User-Agent:" + req.get("User-Agent"));
            break;
        default:
            name.info("msg:" + msg + " user:" + username + " ip:" + req.ip + " url:" + req.originalUrl + " operateType:" + operateType + " operateData:"
                + operateData + " results:" + results + " User-Agent:" + req.get("User-Agent"));
            break;
    }
};

/**
 * 日志保存
 * @param req   request请求,用于获取ip等信息
 * @param operateType   操作类型,例如:0000-登录,1111-退出
 * @param operateData   被操作的数据
 * @param category  日志类别(日志模块类别)
 * @param results   操作结果
 * @param msg   log信息
 * @param logLevel     日志level:info、debug、warn、error、fatal 0-5
 */
helper.saveLog = function (req, operateType, operateData, category, results, msg, logLevel) {
    var username;
    if(typeof req.session.user != "undefined"){
        username = req.session.user.username;
    }else{
        username = req.body.username;
    }
    var logData = {
        'category': category,
        'username': username,
        'agent': req.get("User-Agent"),
        'operateType': operateType,
        'ip': req.ip,
        'operateData': operateData,
        'url': req.originalUrl,
        'results': results,
        'msg': msg,
        'logLevel': logLevel
    };
    dbOperate.insert(logData, "dbo.sysLog", function (results) {
        console.log(results);
    }, "");
};

// 配合express用的方法
exports.use = function (app) {
    //页面请求日志, level用auto时,默认级别是WARN
    app.use(log4js.connectLogger(logInfo, {level: 'INFO'}));        //, format:':method :url'
};

exports.helper = helper;

其中helper.config里面配置log4js:

appenders:数组对象,表示log输出的路径,每一个元素都是一个appender,主要包括:console-控制台输出、dateFile-根据日期配置自动生成当前日期下的日志、file-纯粹在一个文件中输出
type:日志输出类型

pattern:日志输出格式

category:日志类别

alwaysIncludePattern:是否始终以pattern指定格式输出日志

level:日志输出级别

replaceConsole:是否以log4js格式在控制台输出控制台自身log

输出log目录(log目录必须手动先行创建):

log内容:

[2015-09-09 17:46:20.421] [INFO] logInfo - ::1 - - "GET /javascripts/jquery-easyui-1.4.3/themes/default/images/calendar_arrows.png HTTP/1.1" 304 - "http://localhost:3000/javascripts/jquery-easyui-1.4.3/themes/default/easyui.css" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"
[2015-09-09 17:46:26.350] [INFO] logInfo - ::1 - - "POST /user/add HTTP/1.1" 200 16 "http://localhost:3000/user/userManage.html" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"
[2015-09-09 17:46:26.452] [INFO] logInfo - ::1 - - "POST /user/list HTTP/1.1" 200 1966 "http://localhost:3000/user/userManage.html" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"
[2015-09-09 17:46:28.872] [INFO] logInfo - ::1 - - "POST /user/list HTTP/1.1" 200 606 "http://localhost:3000/user/userManage.html" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"
[2015-09-09 17:46:28.883] [INFO] logInfo - ::1 - - "GET /upload/0.3529507869388908.png HTTP/1.1" 304 - "http://localhost:3000/user/userManage.html" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"
[2015-09-09 17:46:28.884] [INFO] logInfo - ::1 - - "GET /upload/0.09649713477119803.png HTTP/1.1" 304 - "http://localhost:3000/user/userManage.html" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"
[2015-09-09 17:46:28.892] [INFO] logInfo - ::1 - - "GET /upload/0.4691608641296625.png HTTP/1.1" 200 27561 "http://localhost:3000/user/userManage.html" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.6 Safari/537.36"

数据库中log表内容:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏bboysoul

使用devstack安装openstack

早就想用devstack去安装openstack了,但是自己的电脑内存才4g真的太小了,最近上了8g内存,果断开虚拟机装devstack。 devstack的...

793
来自专栏Python攻城狮

Python网络爬虫(七)- 深度爬虫CrawlSpider1.深度爬虫CrawlSpider2.链接提取:LinkExtractor3.爬取规则:rules4.如何在pycharm中直接运行爬虫5.

842
来自专栏有趣的django

21天打造分布式爬虫-下载汽车之家图片(九)

953
来自专栏林德熙的博客

win10 uwp httpClient 登陆CSDN

我们可以使用下面代码让 HttpClient 使用 Cookie ,有了这个才可以保存登陆,不然登陆成功下次访问网页还是没登陆。

582
来自专栏pangguoming

vue项目里的日期格式化

在项目中,我们经常需要把后台传回的日期进行格式化,可以在common里定义一个公共的js ? 1 export function formatDate (da...

3877
来自专栏学海无涯

Android开发之DownloadManager的使用

Android 开发中,经常有从服务器下载数据的需求出现,尤其是在线更新App的情形。其基本思路是根据本地的App版本号和服务器的版本号进行比较,如果服务器版本...

3947
来自专栏程序员八阿哥

Python从入门到摔门(7):【总结】浏览器 User-Agent 大全

User Agent中文名为用户代理,是Http协议中的一部分,属于头域的组成部分,User Agent也简称UA。它是一个特殊字符串头,是一种向访问网站提供你...

601
来自专栏木子昭的博客

极简风Js时钟

? <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title...

2717
来自专栏bboysoul

linux编译安装apache

wget http://mirrors.ustc.edu.cn/apache/httpd/httpd-2.4.25.tar.gz tar -zxvf http...

703
来自专栏互联网杂技

Python爬虫,带你制作高逼格的数据聚合云图

一、直接上几张我的博客数据的云图 1.1 爬取文章的标题的聚合 ? ? 1.2 爬取文章的摘要的聚合 1.3 爬取文章的标题+摘要的聚合 我最近写了Sp...

3848

扫码关注云+社区