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 条评论
登录 后参与评论

相关文章

来自专栏Python疯子

iOS加密方式:RSA DES MD5

DES:对称加密(服务器和客户端公用同一个秘钥),缺点:一旦被抓包破解了秘钥,就能破解所有的传递信息

632
来自专栏张绍文的专栏

基于 TLS 1.3的微信安全通信协议 mmtls 介绍(下)

随着近些年网络安全事情的频繁发生,使得用户对网络通信安全的意识越来越强。国内外的网络服务提供商都逐渐提供全站的安全通信服务,如国内的淘宝、百度先后宣布已经完成了...

6551
来自专栏张善友的专栏

各种浏览器的userAgent

各浏览器的userAgent很乱,具体可参看cnbeta上文章译稿:UserAgent的历史变迁。 IE   而IE各个版本典型的userAgent如下: ...

1969
来自专栏杂七杂八

urllib模拟浏览器登录

使用build_opener()修改报头 由于urlopen()不支持一些HTTP的高级功能,所以,我们如果要修改报头,可以使用urllib.request.b...

3145
来自专栏Java架构沉思录

深入浅出密码学(下)

前言 在之前的文章《深入浅出密码学(上)》与《深入浅出密码学(中)》,笔者为大家介绍了密码学中的加密、单向散列函数与消息认证码的概念与应用。这里带大家简单回顾一...

3196
来自专栏云加头条

浅析 HTTPS 与 SSL 原理

HTTPS 是指结合 HTTP 和 SSL 来实现网络浏览器和服务器之间的安全通信。HTTPS 被融合到当今网络操作系统和网络浏览器中,它依赖于网络服务器是否支...

2.6K1
来自专栏java一日一条

详解Https是如何确保安全的?

HTTPS(全称:Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单...

471
来自专栏魏艾斯博客www.vpsss.net

lnmp 怎么看 SSL 证书是否更新了

2494
来自专栏苦逼的码农

【漫画】https 加密那点事

在每次发送真实数据之前,服务器先生成一把密钥,然后先把密钥传输给客户端。之后服务器给客户端发送真实数据的时候,会用这把密钥对数据进行加密,客户端收到加密数据之后...

833
来自专栏java一日一条

详解Https是如何确保安全的?

HTTPS(全称:Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单...

421

扫码关注云+社区