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 服务注入

49830
来自专栏一个会写诗的程序员的博客

RESTFeel: 一个企业级的API管理&测试平台。RESTFeel帮助你设计、开发、测试您的APIRESTFeel功能简介:MongoDB configuration:Building From

The build file is configured to download and use an embedded Tomcat server. So t...

13940
来自专栏10km的专栏

linux下用cmake对caffe静态编译时-static-libstdc++参数无效的问题

以下是用于cmake 生成 Makefile文件对Caffe进行静态库连接编译的shell脚本, #!/bin/bash # cmake 静态编译 caffe-...

1.3K60
来自专栏微信公众号:Java团长

SpringMVC工作原理详解

SpringMVC 框架是以请求为驱动,围绕 Servlet 设计,将请求发给控制器,然后通过模型对象,分派器来展示请求结果视图。其中核心类是 Dispatch...

17310
来自专栏个人分享

spark单机模式简单搭建

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

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

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

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

65070
来自专栏码匠的流水账

聊聊nginx报错499问题

46010
来自专栏代码GG之家

android native内存检测方案(二)

android native 代码内存泄露 定位方案(一) 什么是 AddressSanitizer clang 是一个 C、C++、Objective-C 编...

975100
来自专栏iOSDevLog

Xcode 9 制作 iOS 通用 Framework创建 Framework模拟器和真机通用 FrameworkBundle使用 Framework

51970
来自专栏码神联盟

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

1.8K20

扫码关注云+社区

领取腾讯云代金券