UNPKG

6.66 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 if name of timeFormats# is time vars
117 code += "__vars.now('#{timeFormats[name]}')"
118 else # is vars
119 code += "__vars['#{name}']#{if key then "['#{key}']" else ''}"
120 codes.push '(' + code + '||"-")'
121
122 # push style reset block
123 codes.push '"' + colors.reset + '"' if styles
124 '"+\n' + codes.join('+\n') + '+\n"'
125
126 # remove empty string
127 code = ('"' + code + '"').replace(/^""\+$/mg, '')
128 code = "return #{code.trim()};"
129
130 # __func prefix
131 funcCode = []
132 if funcs.length > 0
133 funcCode.push 'var __func = [];with(__vars||{}){'
134 for [name, key, args] in funcs
135 funcCode.push "__func.push(__vars['#{name}']#{if key then "['#{key}']" else ''}(#{args}));"
136 funcCode.push '}'
137 code = funcCode.join(";\n")+code
138
139 # make function
140 func = new Function('__vars', code)
141 func.stack = useStack # need trace stack for get log position
142 func.time = useTime # need moment for time format
143 func.pattern = pat
144 func
145
146 ###
147 /**
148 * render one line
149 * @param {function} render attern render function (generate by .compile())
150 * @param {string]} msg log messages
151 * @param {string} level log level
152 * @return {string} log line text
153 ###
154 format : (render, msg, level) ->
155 msg = '' if msg is null
156 msg = msg: msg.toString() if typeof msg isnt 'object'
157 msg.color = colors
158 msg.level = levels.text[level]
159 msg.levelTrim = msg.level.trim()
160 if render.time
161 msg.now = getFormatedTime
162 msg.mstimestamp = moment().valueOf()
163 msg.timestamp = Math.floor msg.mstimestamp / 1000
164 msg = trackStack msg if render.stack
165 render(msg) + "\n"
166
167FORMATED_TIME = {}
168
169getFormatedTime = ( format ) ->
170 unless format of FORMATED_TIME
171 #TODO different interval time with difference format
172 interval = 1000
173 timer = ->
174 now = moment()
175 setTimeout(timer, interval-now.milliseconds())
176 FORMATED_TIME[format] = now.format format
177 timer()
178 FORMATED_TIME[format]
179
180trackStack = (msg) ->
181 try
182 throw new Error
183 catch err
184 return stackProcess err, msg
185
186stackProcess = (err, msg) ->
187 stacks = err.stack.split "\n"
188 flag = false
189 for stack in stacks
190 if res = stack.match reg[2]
191 if res[1] isnt justlogPath and res[1] isnt __filename and res[1] isnt anonymous
192 flag = true
193 break
194 if flag is false
195 msg.file = 'NULL'
196 msg.lineno = 0
197 else
198 file = res[1]
199 msg.file = if file[0] is '/' then path.relative cwd, file else file
200 msg.lineno = res[2]
201 msg.stack = "#{msg.file}:#{msg.lineno}"
202 msg.stackColored = "#{colors.underline}#{colors.cyan}#{msg.file}:#{colors.yellow}#{msg.lineno}#{colors.reset}"
203 msg