OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library shelf.handlers.logger; |
| 6 |
| 7 import 'package:stack_trace/stack_trace.dart'; |
| 8 |
| 9 import '../middleware.dart'; |
| 10 import '../util.dart'; |
| 11 |
| 12 /// Middleware which prints the time of the request, the elapsed time for the |
| 13 /// inner handlers, the response's status code and the request URI. |
| 14 /// |
| 15 /// [logger] takes two paramaters. |
| 16 /// |
| 17 /// `msg` includes the request time, duration, request method, and requested |
| 18 /// path. |
| 19 /// |
| 20 /// For successful requests, `msg` also includes the status code. |
| 21 /// |
| 22 /// When an error is thrown, `isError` is true and `msg` contains the error |
| 23 /// description and stack trace. |
| 24 Middleware logRequests({void logger(String msg, bool isError)}) => |
| 25 (innerHandler) { |
| 26 if (logger == null) logger = _defaultLogger; |
| 27 |
| 28 return (request) { |
| 29 var startTime = new DateTime.now(); |
| 30 var watch = new Stopwatch()..start(); |
| 31 |
| 32 return syncFuture(() => innerHandler(request)).then((response) { |
| 33 var msg = _getMessage(startTime, response.statusCode, request.pathInfo, |
| 34 request.method, watch.elapsed); |
| 35 |
| 36 logger(msg, false); |
| 37 |
| 38 return response; |
| 39 }, onError: (error, stackTrace) { |
| 40 var msg = _getErrorMessage(startTime, request.pathInfo, request.method, |
| 41 watch.elapsed, error, stackTrace); |
| 42 |
| 43 logger(msg, true); |
| 44 |
| 45 throw error; |
| 46 }); |
| 47 }; |
| 48 }; |
| 49 |
| 50 String _getMessage(DateTime requestTime, int statusCode, String pathInfo, |
| 51 String method, Duration elapsedTime) { |
| 52 |
| 53 return '${requestTime}\t$elapsedTime\t$method\t[${statusCode}]\t${pathInfo}'; |
| 54 } |
| 55 |
| 56 String _getErrorMessage(DateTime requestTime, String pathInfo, |
| 57 String method, Duration elapsedTime, Object error, StackTrace stack) { |
| 58 |
| 59 var chain = new Chain.current(); |
| 60 if (stack != null) { |
| 61 chain = new Chain.forTrace(stack) |
| 62 .foldFrames((frame) => frame.isCore || frame.package == 'shelf') |
| 63 .terse; |
| 64 } |
| 65 |
| 66 var msg = '${requestTime}\t$elapsedTime\t$method\t${pathInfo}\n$error'; |
| 67 if(chain == null) return msg; |
| 68 |
| 69 return '$msg\n$chain'; |
| 70 } |
| 71 |
| 72 void _defaultLogger(String msg, bool isError) { |
| 73 if (isError) { |
| 74 print('[ERROR] $msg'); |
| 75 } else { |
| 76 print(msg); |
| 77 } |
| 78 } |
OLD | NEW |