Skip to content

Instantly share code, notes, and snippets.

@jirkapenzes
Created January 31, 2022 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jirkapenzes/9f3dd2655df6d8a6023efb354f709412 to your computer and use it in GitHub Desktop.
Save jirkapenzes/9f3dd2655df6d8a6023efb354f709412 to your computer and use it in GitHub Desktop.
import 'package:easy_localization/easy_localization.dart';
final flogger = Logger();
final logger = Logger();
class Logger {
bool debug = true;
log(String message) {
final currentDate = DateTime.now();
final formattedDate = '${DateFormat('dd.MM.yyyy HH:mm:ss').format(currentDate)}';
if (debug) {
final info = _StackTraceInfo.fromStackTrace(StackTrace.current);
print('$formattedDate: ${info.className}->${info.functionName}() [${info.lineNumber}]: $message');
} else {
print(message);
}
}
}
log(String message) => logger.log(message);
info(String message) => logger.log(message);
warn(String message) => logger.log(message);
warning(String message) => logger.log(message);
class _StackTraceInfo {
final String className;
final String functionName;
final String fileName;
final int lineNumber;
const _StackTraceInfo({
required this.className,
required this.functionName,
required this.fileName,
required this.lineNumber,
});
factory _StackTraceInfo.fromStackTrace(StackTrace stackTrace) {
try {
final traceStringLines =
stackTrace.toString().split("\n").where((element) => !element.contains('logger.dart')).toList();
if (traceStringLines.length >= 1) {
final currentTraceString = traceStringLines[0];
final regex = RegExp(
r'#[1-9]+[\s]+(?<class>[\w]+).(?<function>[\w]+) \(package:(?<file>[\w/.]+):(?<line>[1-9]+):(?<column>[1-9]+)\)$');
final match = regex.firstMatch(currentTraceString);
if (match != null) {
final className = match.namedGroup('class') ?? '';
final functionName = match.namedGroup('function') ?? '';
final fileName = match.namedGroup('file') ?? '';
final lineNumber = match.namedGroup('line') ?? '';
return _StackTraceInfo(
className: className,
functionName: functionName,
fileName: fileName,
lineNumber: int.parse(lineNumber),
);
}
}
} catch (_) {}
return _StackTraceInfo.nullable();
}
factory _StackTraceInfo.nullable() {
return _StackTraceInfo(className: '', functionName: '', fileName: '', lineNumber: -1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment