UNPKG

6.29 kBtext/coffeescriptView Raw
1# coffee = require 'coffee-script'
2moment = require 'moment'
3colors = require './colors'
4path = require 'path'
5levels = require './levels'
6
7cwd = process.cwd()
8reg = [
9 /\b(file|lineno|stack|stackColored)\b/
10 /\b(now|time|date|fulltime|numbertime|mstimestamp|timestamp|moment)\b/
11 /\(([^\)\(]+?):(\d+):\d+\)$/]
12stackNames = ['file', 'lineno', 'stack', 'stackColored']
13timeNames = ['now', 'time', 'date', 'fulltime', 'numbertime', 'mstimestamp', 'timestamp']
14
15timeFormats =
16 time : 'HH:mm:ss'
17 date : 'YYYY-MM-DD'
18 fulltime : 'YYYY-MM-DD HH:mm:ss'
19 numbertime : 'YYYYMMDDHHmmss'
20
21justlogPath = __dirname + '/log' + path.extname __filename
22
23anonymous = '<anonymous>'
24
25module.exports = pattern =
26 ###
27 /**
28 * pre-defined log patterns
29 * @type {object}
30 * colored :
31 * - simple-color: log message and colored level text
32 * - simple-nocolor: like simple without color
33 * - color: tracestack, time, log message and colored level text
34 * nocolor :
35 * - nocolor: like color without color
36 * - event-color: time, log message and colored event
37 * nocolor :
38 * - event-nocolor: like event-color without color
39 * - file : fulltime, tracestack, log message and level text
40 * connect-middleware : ()
41 * - accesslog: apache access-log
42 * - accesslog-rt: like access-log with response-time on the end (with microsecond)
43 * - accesslog-color: like ACCESSLOG-RT with ansi colored
44 ###
45 pre :
46 'simple-nocolor' : '{level} {msg}'
47 'simple-color' : '{color.level level} {msg}'
48 'nocolor' : '{time} [{levelTrim}] ({stack}) {msg}'
49 'color' : '{time} {color.level level} {stackColored} {msg}'
50 'file' : '{fulltime} [{levelTrim}] ({stack}) {msg}'
51 'event-color' : '{time} {color.event event} {args}'
52 'event-nocolor' : '{fulltime} {event} {args}'
53 'accesslog' : '''
54 {remote-address} {ident} {user}
55 [{now "DD/MMM/YYYY:HH:mm:ss ZZ"}]
56 "{method} {url} HTTP/{version}"
57 {status} {content-length}
58 "{headers.referer}" "{headers.user-agent}"
59 '''.replace /\n/g, ' '
60 'accesslog-rt' : '''
61 {remote-address} {ident} {user}
62 [{now 'DD/MMM/YYYY:HH:mm:ss ZZ'}]
63 "{method} {url} HTTP/{version}"
64 {status} {content-length}
65 "{headers.referer}" "{headers.user-agent}" {rt}
66 '''.replace /\n/g, ' '
67 'accesslog-color' : '''
68 {remote-address@yellow} {ident} {user}
69 [{now 'DD/MMM/YYYY:HH:mm:ss ZZ'}]
70 "{color.method method} {url@underline,bold,blue} HTTP/{version}"
71 {color.status status} {content-length}
72 "{headers.referer@blue}" "{headers.user-agent@cyan}" {rt}
73 '''.replace /\n/g, ' '
74
75 ###
76 /**
77 * compile log-format pattern to a render function
78 * @param {string} code pattern string
79 * @return {function} pattern render function
80 * - {bool} [trace] need tracestack info
81 * - {bool} [time] need logtime info
82 * - {string} [pattern] pattern text
83 ###
84 compile : (pat)->
85 code = pattern.pre[pat] ? pat # check perdefines
86 code = code.replace /"/g, '\\"' # slash '"'
87 useStack = false
88 useTime = false
89 # match all tokens
90 funcs = []
91 code = code.replace ///
92 \{
93 ([a-zA-Z][\-\w]+) # var name
94 (?:\.([\w\-]+))? # sub key name
95 (?:\s([^}@]+?))? # function args
96 (?:@((?:[a-z_]+,?)+))? # style
97 \}
98 ///g, (match, name, key, args, style) ->
99 useStack = true if name in stackNames # need tracestack
100 useTime = true if name in timeNames # need time
101 codes = []
102
103 # push style block
104 code = ''
105 styles = style.split ',' if style
106 if styles
107 code += colors[style] for style in styles
108 codes.push '"' + code + '"'
109
110 # push vars block
111 code = ''
112 if args # is function
113 num = funcs.length
114 funcs.push [name, key, args.replace(/\\"/g, '"')]
115 code = "__func[#{num}]"
116 else # is vars
117 code += "__vars['#{name}']#{if key then "['#{key}']" else ''}"
118 codes.push '(' + code + '||"-")'
119
120 # push style reset block
121 codes.push '"' + colors.reset + '"' if styles
122 '"+\n' + codes.join('+\n') + '+\n"'
123
124 # remove empty string
125 code = ('"' + code + '"').replace(/^""\+$/mg, '')
126 code = "return #{code.trim()};"
127
128 # __func prefix
129 funcCode = []
130 if funcs.length > 0
131 funcCode.push 'var __func = [];with(__vars||{}){'
132 for [name, key, args] in funcs
133 funcCode.push "__func.push(__vars['#{name}']#{if key then "['#{key}']" else ''}(#{args}));"
134 funcCode.push '}'
135 code = funcCode.join(";\n")+code
136
137 # make function
138 func = new Function('__vars', code)
139 func.stack = useStack # need trace stack for get log position
140 func.time = useTime # need moment for time format
141 func.pattern = pat
142 func
143
144 ###
145 /**
146 * render one line
147 * @param {function} render attern render function (generate by .compile())
148 * @param {string]} msg log messages
149 * @param {string} level log level
150 * @return {string} log line text
151 ###
152 format : (render, msg, level) ->
153 msg = '' if msg is null
154 msg = msg: msg.toString() if typeof msg isnt 'object'
155 msg.color = colors
156 msg.level = levels.text[level]
157 msg.levelTrim = msg.level.trim()
158 if render.time
159 now = moment()
160 msg[k] = now.format v for k,v of timeFormats
161 msg.now = now.format.bind now
162 msg.mstimestamp = now.valueOf()
163 msg.timestamp = Math.floor msg.mstimestamp / 1000
164 if render.stack
165 try
166 throw new Error
167 catch err
168 stacks = err.stack.split "\n"
169 flag = false
170 for stack in stacks
171 if res = stack.match reg[2]
172 if res[1] isnt justlogPath and res[1] isnt __filename and res[1] isnt anonymous
173 flag = true
174 break
175 if flag is false
176 msg.file = 'NULL'
177 msg.lineno = 0
178 else
179 file = res[1]
180 msg.file = if file[0] is '/' then path.relative cwd, file else file
181 msg.lineno = res[2]
182 msg.stack = "#{msg.file}:#{msg.lineno}"
183 msg.stackColored = "#{colors.underline}#{colors.cyan}#{msg.file}:#{colors.yellow}#{msg.lineno}#{colors.reset}"
184 render(msg) + "\n"
185