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

相关文章

来自专栏IT进修之路

原 荐 最新SpringCloud 服务注入

3103
来自专栏向治洪

ActivityManagerService启动过程分析

之前讲Android的View的绘制原理和流程的时候,讲到过在Android调用setContentView之后,Android调用了一个prepreTravl...

2278
来自专栏搜云库

Spring Boot 中使用 MyBatis 整合 Druid 多数据源

本文将讲述 spring boot + mybatis + druid 多数据源配置方案。 环境 CentOs7.3 安装 MySQL 5.7.19 二进制版本...

2977
来自专栏微服务那些事儿

Spring Cloud 系列-事件监听

强推一波:https://segmentfault.com/ls/1650000011386794

2044
来自专栏个人分享

spark单机模式简单搭建

待安装列表 hadoop hive scala spark 一.环境变量配置: ~/.bash_profile PATH=$PATH:$HOME/bin

3141
来自专栏码神联盟

框架 | SpringBoot项目发布部署外部tomcat服务器步骤

1.1K2
来自专栏菩提树下的杨过

spring cloud:config-server中@RefreshScope的"陷阱"

spring cloud的config-serfver主要用于提供分布式的配置管理,其中有一个重要的注解:@RefreshScope,如果代码中需要动态刷新配置...

4567
来自专栏码匠的流水账

聊聊nginx报错499问题

1271
来自专栏菩提树下的杨过

jboss eap 6.3 集群(cluster)-Session 复制(Replication)

本文算是前一篇的后续,java web application中,难免会用到session,集群环境中apache会将http请求智能转发到其中某台jboss ...

3127
来自专栏运维小白

11.22 访问日志不记录静态文件

访问日志不记录指定类型的文件目录概要 网站大多元素为静态文件,如图片、css、js等,这些元素可以不用记录 把虚拟主机配置文件改成如下: <VirtualHo...

3116

扫码关注云+社区