GithubHelp home page GithubHelp logo

sourcehorizon / logger Goto Github PK

View Code? Open in Web Editor NEW
197.0 2.0 33.0 685 KB

Small, easy to use and extensible logger which prints beautiful logs.

Home Page: https://pub.dev/packages/logger

License: MIT License

Dart 100.00%

logger's Introduction

Logger

pub package CI Last Commits Pull Requests Code size License

Small, easy to use and extensible logger which prints beautiful logs.
Inspired by logger for Android.

Show some ❤️ and star the repo to support the project

Resources:

Getting Started

Just create an instance of Logger and start logging:

var logger = Logger();

logger.d("Logger is working!");

Instead of a string message, you can also pass other objects like List, Map or Set.

Output

Documentation

Log level

You can log with different levels:

logger.t("Trace log");

logger.d("Debug log");

logger.i("Info log");

logger.w("Warning log");

logger.e("Error log", error: 'Test Error');

logger.f("What a fatal log", error: error, stackTrace: stackTrace);

To show only specific log levels, you can set:

Logger.level = Level.warning;

This hides all trace, debug and info log events.

Options

When creating a logger, you can pass some options:

var logger = Logger(
  filter: null, // Use the default LogFilter (-> only log in debug mode)
  printer: PrettyPrinter(), // Use the PrettyPrinter to format and print log
  output: null, // Use the default LogOutput (-> send everything to console)
);

If you use the PrettyPrinter, there are more options:

var logger = Logger(
  printer: PrettyPrinter(
      methodCount: 2, // Number of method calls to be displayed
      errorMethodCount: 8, // Number of method calls if stacktrace is provided
      lineLength: 120, // Width of the output
      colors: true, // Colorful log messages
      printEmojis: true, // Print an emoji for each log message
      // Should each log print contain a timestamp
      dateTimeFormat: DateTimeFormat.onlyTimeAndSinceStart,
  ),
);

Auto detecting

With the io package you can auto detect the lineLength and colors arguments. Assuming you have imported the io package with import 'dart:io' as io; you can auto detect colors with io.stdout.supportsAnsiEscapes and lineLength with io.stdout.terminalColumns.

You should probably do this unless there's a good reason you don't want to import io, for example when using this library on the web.

LogFilter

The LogFilter decides which log events should be shown and which don't.
The default implementation (DevelopmentFilter) shows all logs with level >= Logger.level while in debug mode (i.e., running dart with --enable-asserts). In release mode all logs are omitted.

You can create your own LogFilter like this:

class MyFilter extends LogFilter {
  @override
  bool shouldLog(LogEvent event) {
    return true;
  }
}

This will show all logs even in release mode. (NOT a good idea)

LogPrinter

The LogPrinter creates and formats the output, which is then sent to the LogOutput.
You can implement your own LogPrinter. This gives you maximum flexibility.

A very basic printer could look like this:

class MyPrinter extends LogPrinter {
  @override
  List<String> log(LogEvent event) {
    return [event.message];
  }
}

If you created a cool LogPrinter which might be helpful to others, feel free to open a pull request. :)

Colors

Please note that in some cases ANSI escape sequences do not work under macOS. These escape sequences are used to colorize the output. This seems to be related to a Flutter bug that affects iOS builds: flutter/flutter#64491

However, if you are using a JetBrains IDE (Android Studio, IntelliJ, etc.) you can make use of the Grep Console Plugin and the PrefixPrinter decorator to achieve colored logs for any logger:

var logger = Logger(
    printer: PrefixPrinter(PrettyPrinter(colors: false))
);

LogOutput

LogOutput sends the log lines to the desired destination.
The default implementation (ConsoleOutput) send every line to the system console.

class ConsoleOutput extends LogOutput {
  @override
  void output(OutputEvent event) {
    for (var line in event.lines) {
      print(line);
    }
  }
}

Possible future LogOutputs could send to a file, firebase or to Logcat. Feel free to open pull requests.

Acknowledgments

This package was originally created by Simon Choi, with further development by Harm Aarts, greatly enhancing its functionality over time.

logger's People

Contributors

audkar avatar bungeefan avatar defuncart avatar devnico avatar ewertonrp avatar filipedfs avatar gkuga avatar gmpassos avatar haarts avatar hidan4 avatar jonasfj avatar lomby92 avatar marcgraub avatar myconsciousness avatar narumi147 avatar pyciko avatar simc avatar smotastic avatar stitch-taotao avatar timmaffett avatar tkutcher avatar yangsfang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

logger's Issues

Encoding issue

This case is on web (console) but I think it happens in sever (file).

log.t('Websocket connection -- On done (Stream) -- $id');

Prints in web console this:

�[38;5;244m[T]�[0m  Websocket connection -- On done (Stream) -- [NOT SET YET]

It is weird because it is printing okay this:

[D]  Connecting to Webosckets Server

My logger is:

Logger(
      level: use(appCapsule).logLevel.casted,  // trace
      filter: ProductionFilter(),
      output: ConsoleOutput(),
      printer: SimplePrinter(),
    )

Long text support

Hi, I have an issue when trying to log long text like the JWT token

image

For the first line from the logger
and the second line is from log dart:developer

iOS: Colors not working

I was trying to understand why colors are not supported in VSCode and read the comment in the ReadMe.md

Please note that all IDEs (VSCode, XCode, Android Studio, IntelliJ) do not support ANSI escape sequences in their terminal outputs. These escape sequences are used to color output. If using such an IDE do not configure colored output.

However, one of the dev_dependencies that I am using is working perfectly with colors!

Any idea why this is not working for main project?

This is the dev dependency: https://pub.dev/packages/pubspec_dependency_sorter

Screenshot 2023-04-15 at 11 54 28 PM

Web issues

When transpiling for Dart Web I got this warning, which is fatal because it breaks the transpile:

[WARNING] build_web_compilers:entrypoint on web/main.dart: Skipping compiling my_project|web/main.dart with dart2js because some of its
transitive libraries have sdk dependencies that are not supported on this platform:

logger|lib/src/outputs/file_output_stub.dart

https://github.com/dart-lang/build/blob/master/docs/faq.md#how-can-i-resolve-skipped-compiling-warnings

I tried to bypass it by replacing this:

import 'package:logger/logger.dart'

into this:

import 'package:logger/src/logger.dart';
import 'package:logger/src/filters/production_filter.dart';
import 'package:logger/src/outputs/console_output.dart';
import 'package:logger/src/printers/simple_printer.dart';
import 'package:logger/src/log_level.dart';

which leads to these static warnings (non-fatal), but the fatal warning still not solved:

Import of a library in the 'lib/src' directory of another package.
Try importing a public library that exports this library, or removing the import

Firstly I want to solve the fatal warning: Is there a way to import in a web safe way?

Secondly, would be great that the first solution also removes the non fatal warnings.

Thanks

Async Init Methods in Constructor

I've encountered an issue related to the initialization process within the Logger class, specifically around its constructor behavior when dealing with asynchronous initialization methods like LogOutput.init. In my use case, I've implemented a custom LogOutput that requires awaiting some resources in its init method. However, I've noticed that the output method of LogOutput gets invoked before the init method has had a chance to fully complete.

This behavior stems from the fact that asynchronous methods cannot be awaited directly within constructors in Dart. This presents a challenge for ensuring that all necessary asynchronous initialization is completed before the Logger instance starts invoking methods that depend on that initialization.

To address this issue, I propose the introduction of an asynchronous factory method. This method would perform the necessary await operations on the initialization calls and only resolve with an instance of the Logger class once all asynchronous setup is fully completed. This change would ensure that instances of Logger are fully initialized and ready to use, avoiding premature method calls that assume initialization has already occurred.

Adapt the severities/levels of Syslog (Unix)

Hello, folks.

I'm little confused with Level.nothing. It's an accessible log level from another context but the log function throw an Exception('Log events cannot have Level.nothing').

What is the point to have this level?

Add web compatibility?

Any plans on making this package compatible with the web platform? According to Pana analysis, it's not compatible because it imports dart:io.

Package not compatible with platform Web

Because:

  • package:logger/logger.dart that imports:
  • package:logger/src/outputs/file_output_stub.dart that imports:
  • dart:io

weird behaviour while using logger with workmanager

Hi,

I wanted to log a message based on the result of the work manager job in my app. So on success run, it shows ran successfully or error in case of failure run. So I checked in the case of success run and this is what i got in the logs:

console logs
I/flutter (10449): │ #0   callbackDispatcher.<anonymous closure> (package:weatherwise/main.dart:97:18)
main.dart:97
I/flutter (10449): │ #1   <asynchronous suspension>
I/flutter (10449): │ 💡 Scheduled job ran successfully!

it throw some exception of some kind?

This is my work manager code with logger:

code
  Workmanager().executeTask((task, inputData) async {
    switch (task) {
      case "currentWeather":
        final sharedPreference = await SharedPreferences.getInstance();

        try {
          final weatherResponse = await WidgetService()
              .getWidgetWeather(sharedPreference.getString('activeKey') ?? "");

          WidgetService().updateWidget(weatherResponse);
          logger.i("Scheduled job ran successfully!");
        } catch (e) {
          logger.e(
            'Error occurred while fetching weather:',
            error: e,
          );
        }

        return Future.value(true);
    }
    return Future.value(true);
  });

Log Listener

I am using Logger in my project and thanks for your effort but I am looking for an integration with Firebase Crashlytics.
For example, if I use logger.severe I want to send it to the Firebase. Of course, the easiest way is to send it just below logger.severe but if there's a more centric approach like global listener for different levels I can send it there.

Logger.close() should return Future<void>

The implementation of Logger.close() nicely destroys the _output, but if the _output is a FileOutput, that destroy function is async void.

// logger.dart
void close() {
  _active = false;
  _filter.destroy();
  _printer.destroy();
  _output.destroy();
}
// file_output.dart
@override
void destroy() async {
  await _sink?.flush();
  await _sink?.close();
}

It would be a best practice to let Logger await the destroy function and make destroy return a Future<void>.

// logger.dart
Future<void> close() async {
  _active = false;
  _filter.destroy();
  _printer.destroy();
  await _output.destroy();
}
// file_output.dart
@override
Future<void> destroy() async {
  await _sink?.flush();
  await _sink?.close();
}

Doing so makes it possible in a unit test to await the close function before actually deleting the temporary folder.

[Feature] Add 'TAG' options

Is there a chance to add a tag feature to the logger?

There was already a PR on the old repo:
[Feature] Add 'TAG' options #103

And here is a discussion:
simc/logger#68 (comment)

The reason for this is, if you have multiple components for example, I use get_it to inject my logger into these components to collect all log data in one place (FileOutput, whatever.). But I can't figure out which log comes from what component. Maybe just an optional tag attribute like the guy did in the PR.

Broken file output

Hello,
I have the problem that the logger unfortunately does not send all log events to the file log output, or that some of them are written broken to the file.
The console output works without any problems.
As an example I have here the file output and the console output.
File output:

[I] TIME: 2023-12-25T14:11:13.242861 FluxNews - initializeDB : Starting initializeDB
ig values[I] TIME: 2023-12-25T14:11:13.264610 FluxNews - initializeDB : Finished initializeDB
[I] TIME: 2023-12-25T14:11:13.353699 FluxNews - renewAllNewsCount : Starting
rene
ing all news c
unt
ter
[I] TIME: 2023-12-25T14:11:13.371997 FluxNews - queryNewsFromDB : Finished querying news from DB[I] TIME: 2023-12-25T14:11:13.373921 FluxNews - updateNewsStatusInDB : Finished updating starred counter
[I] TIME: 2023-12-25T14:11:13.376115 FluxNews - renewAllNewsCount : Finished renewing all news count
[I] TIME: 2023-12-25T14:11:13.427975 FluxNews - queryCategoriesFromDB : Finished querying categories
from DB[I] TIME: 2023-12-25T14:11:13.429207 FluxNews - renewAllNewsCount : Finished renewing all news count

Console output:

flutter: [I] TIME: 2023-12-25T14:11:13.240602 FluxNews - readConfigValues : Finished read config values
flutter: [I] TIME: 2023-12-25T14:11:13.242861 FluxNews - initializeDB : Starting initializeDB
flutter: [I] TIME: 2023-12-25T14:11:13.248581 FluxNews - initializeDB : Finished initializeDB
flutter: [I] TIME: 2023-12-25T14:11:13.264610 FluxNews - initializeDB : Finished initializeDB
flutter: [I] TIME: 2023-12-25T14:11:13.349413 FluxNews - readConfig : Starting read config
flutter: [I] TIME: 2023-12-25T14:11:13.350533 FluxNews - module : Value: Oldest first
flutter: [I] TIME: 2023-12-25T14:11:13.351978 FluxNews - readConfig : Finished read config
flutter: [I] TIME: 2023-12-25T14:11:13.352651 FluxNews - queryNewsFromDB : Starting querying news from DB
flutter: [I] TIME: 2023-12-25T14:11:13.353424 FluxNews - updateNewsStatusInDB : Starting updating starred counter
flutter: [I] TIME: 2023-12-25T14:11:13.353699 FluxNews - renewAllNewsCount : Starting renewing all news count
flutter: [I] TIME: 2023-12-25T14:11:13.371997 FluxNews - queryNewsFromDB : Finished querying news from DB
flutter: [I] TIME: 2023-12-25T14:11:13.373921 FluxNews - updateNewsStatusInDB : Finished updating starred counter
flutter: [I] TIME: 2023-12-25T14:11:13.376115 FluxNews - renewAllNewsCount : Finished renewing all news count
flutter: [I] TIME: 2023-12-25T14:11:13.427651 FluxNews - renewAllNewsCount : Starting renewing all news count
flutter: [I] TIME: 2023-12-25T14:11:13.427975 FluxNews - queryCategoriesFromDB : Finished querying categories from DB
flutter: [I] TIME: 2023-12-25T14:11:13.429207 FluxNews - renewAllNewsCount : Finished renewing all news count

This is the code that is used for logging:

import 'dart:io';

import 'package:flux_news_desktop/flux_news_state.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';

void logThis(
    String module, String message, Level loglevel, FluxNewsState appState) {
  if (appState.loggingFilePath != "") {
    DateTime now = DateTime.now();
    DateFormat formatter = DateFormat('yyyy-MM-dd');
    String formattedDate = formatter.format(now);
    File logFile =
        File('${appState.loggingFilePath}/FluxNewsLogs-$formattedDate.txt');
    String logMessage = "${FluxNewsState.logTag} - $module : $message";
    Logger logger = Logger(
      filter: ProductionFilter(),
      printer: SimplePrinter(printTime: true, colors: false),
      output: MultiOutput([FileOutput(file: logFile), ConsoleOutput()]),
    );
    logger.log(loglevel, logMessage);
  } else {
    String logMessage = "${FluxNewsState.logTag} - $module : $message";
    Logger logger = Logger(
      printer: PrettyPrinter(methodCount: 0),
    );
    logger.log(loglevel, logMessage);
  }
}

Investigate adoption of dart's developer `log` signature

Adopting the same (or similar) signature as dart:developer.log would have several benefits:

  • Making it easier to migrate to this package.
  • No need to provide null for the error object to provide a stack trace.
  • Would allow additions of more optional features like the one in #11.

Feel free to add your comments and ideas to this issue!

truncated log message in iOS

When outputting iOS logs, I see the message <...> at the end of my logs but not in the same log on the Android emulator.

iOS:

Reloaded 1 of 710 libraries in 177ms (compile: 18 ms, reload: 66 ms, reassemble: 75 ms).
flutter: ^[[38;5;12m┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>
flutter: ^[[38;5;12m│ 💡 test Screen<…>
flutter: ^[[38;5;12m└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>

Android:

Restarted application in 1,068ms.
I/flutter ( 9044): ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter ( 9044): │ test Screen
I/flutter ( 9044): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

--enable-asserts shows message on screen

When I ran example "example/main.dart":

dart ./example/main.dart -> no message are printed on screen (messages are printed in debug console)

dart --enable-asserts ./example/main.dart -> messages are printed on screen

Can you explain me why? is that behaviour normal?

Error while using this package.

This is the error log
──────
I/flutter ( 6257): │ #0 _MyHomePageState._incrementCounter (package:flutter_design/main.dart:46:12)
main.dart:46
I/flutter ( 6257): │ #1 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1096:21)
ink_well.dart:1096
I/flutter ( 6257): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄

Add time to log output

Is there a way to add time to the log output? This will be useful during debugging an issue.

v2 log signature changed

note for those about to get hit by this, esp if your CI server makes test fails not obvious the actual error, doh

I was/am using like so

 log.w(err, "some msg");

You have just published new version, I need to upgrade I guess...

And for now I pin to v1 doh

  # log signature changed in 2.x
  logger: ^1.4.0

Would recommend update readme to show usage of additional args tho

Documentation
Log level
You can log with different levels:

logger.t("Trace log");

logger.d("Debug log");

logger.i("Info log");

logger.w("Warning log");

logger.e("Error log");

logger.f("What a fatal log");


right, named args ok..

d(dynamic message, {DateTime? time, Object? error, StackTrace? stackTrace}) → void
Log a message at level Level.debug.

Reading .ans files & Flutter system errors to log

I made my application logs to file, it working just fine but I have several questions:

First

What do I do with this text file? I mean when you try to read it in a normal text reader like Notepad++ or Vs Code you will se some 'ESC' or color chars thats not working. Is there any extensions kinda thing (that I searched but couldn't found) that reads that ansi color and changes the line's color acourding to it? Is there a way to convert those 'ESC' and '[0m' (end of line I guess) chars to something else automaticly.

Log file view

Screenshot 2023-11-02 113822

Second

Can I log the systems/flutter's logs to the same file too? If there will be an other error like widget cant fit to the screen or something, the flutter it self would log it to the console but the file output wont contain it. Also in release mode how to log these logs to the file.

Note: I know this is most likely a stackoverflow question but im asking here bc maybe someone tryed to log the system logs to this package before. If there is no other solution than logging to seperate file you can ignore this question.

Rework `LogFilter.level`

This is the cause of a pretty weird bug:

final filter = ProductionFilter();
final logger = Logger(filter: filter);

void main() {
  filter.level = Level.warning;
  logger.i("This is an info message and should not show");  // it shows
}

Took me a while to isolate the problem, but it is because logger is lazily evaluated:

class MyFilter extends LogFilter {
	Level _level = Level.info;
	@override Level get level => _level;	
	@override set level(Level? value) {
		print("Setting log level to $value");
		_level = value ?? Level.info;
	}

	@override	
	bool shouldLog(LogEvent event) => event.level.index >= level.index;
}

final filter = MyFilter();
final logger = Logger(filter: filter, printer: SimplePrinter())..toString();

void main() {
  filter.level = Level.warning;
  logger.i("This is an info message and should not show");  // it shows
}
 // Output: 
 // Setting level to warning
// Setting level to verbose
// [I] This is an info message and should not show

Turns out, when logger is accessed for the first time, its constructor sets filter.level = Logger.level, overriding any previous assignment. This should be removed so we can configure the log level of a global logger

Allow switching out default DevelopmentFilter globally

Asserts are expensive per Flutter doc

It is better to use kDebugMode when using Flutter (which I believe will be true for a majority of the user). Since kDebugMode is a constant, the compiler can optimize away the conditional check making it much faster than assert().

But since this project is dart only, we cannot introduce a dependency on package:flutter/foundation.dart because it will break the minority of users who are dart only. So it would be the best to allow the user to switch out the implementation of the DevelopmentFilter.

While currently it is already possible to pass filter to every Logger() call, it is much cleaner if this can be done globally.

The proposal is to allow switching out the implementation similar to Logger.level.

[PrettyPrinter] Error Color: Force foreground color to white

I am creating this issue to pick up this pull request: simc/logger#137

Summary

PrettyPrinter: Force the foreground color always to white for the red and pink background color.

Status

Currently, foreground color isn't set therefore, the terminal will use the default foreground color to write on the error/wtf background, whichever that it.

Discussion

As far as I am aware, both VSC and Android Studio uses a good contrast color for the foreground, which should provide a good readability when writing on the terminal default background (which we are not when printing the error message).
Therefore, forcing no foreground color can result in a worse readability, depending on the theme settings of the terminal and so on.

Please share your opinions and ideas on this topic!

My opinion

I did never experience great readability with a bright red background, yes some colors and combinations are better, but it's just not really enjoyable trying to read the error message.
I see no point in painting the error with a bright red background when everything else in the log is already screaming for attention.

I would remove the additional background color of the error as a whole and treat it the same way as the other text in the error log.

Please add "success" in green.

I monitor requests and responses using a logger. In this case, I would like to use a green log for a successful request.

Getting <anonymous closure> <asynchronous suspension> using logger in Async Function

Logger works seemingly normally except in async functions, where it still outputs the desired log but gets extra exceptions thrown compared to print. I tested this in two places. Here is a minimal example of my settings.
TestDelHTTP.<anonymous closure> is thrown in every call to lg.d, and TestDelHTTP.<asynchronous suspension> is thrown in the "then" block, but no exceptions are thrown just using print.

Map<Level, String> customLevelEmojis = {
  Level.trace: '🔦',
  Level.debug: '🖌',
  Level.info: 'ℹ️',
  Level.warning: '⚠️',
  Level.error: '🚫',
  Level.fatal: '👾',
};

Logger lg = Logger(
  printer: PrettyPrinter(levelEmojis: customLevelEmojis ),
  level: Level.debug
);

TestDelHTTP(
    WidgetRef ref,
    String opDescription,
    Function showErrorDialog,
    Function showOpResultsPage
    )async {
  ref.read(opIsRunningProv.notifier).state = true;
  ref.read(opDescriptionProv.notifier).state = opDescription;
  lg.d("test del http");
    await http.post(
      Uri.parse("https://10.0.2.2:1515/test_del_http"),
      headers: {'Content-Type': 'application/json',},
    ).then((resp){
      lg.d("Test Del HTTP RESP ~ " + resp.body);
      showOpResultsPage(resp.body);
    }).catchError((error){
      lg.d("error testing del http " + error);
      lg.d("test del http error");
      showErrorDialog(error);
  }).whenComplete((){
      lg.d("test del http complete");
    ref.read(opDescriptionProv.notifier).state = "";
    ref.read(opIsRunningProv.notifier).state = false;
  });

}

Logging not shown at all.

How to Reproduce

  1. Create a Dart project.
$ dart create abc
$ cd abc
$ dart pub add logger
  1. Edit bin/abc.dart.
import 'package:logger/logger.dart';

void main() {
  final logger = Logger(level: Level.debug);
  logger.i("hello");
}
  1. Run.
$ dart run #Nothing is printed.

Workaround

When I execute dart run --enable-asserts instead of dart run, the log is printed.

Reading the official documentation, I couldn't find any section in which the need of --enable-asserts option is referred to. In addition, how can I enable logging when compiling a program with dart compile exe, given --enable-asserts cannot be specified in that context?

Poor information in LogEvent

Hello, folks!
Thank you for maintaining this project.

I would like to know if there is any prediction in the future to implement more information in the LogEvent class. In some logger implementations like Python, whose LogRecord equivalent, some information is passed as lineno, module, funcName, etc. It would be interesting because it would be used when issuing a log to some other log system like DataDog or Graylog.

Not writing logs to file in release mode

Code :

Future<File> _getFileName(
      {bool forCreate = true, DateTime? requiredDate}) async {
    DateTime date = requiredDate ?? DateTime.now();
    Directory directory = Directory(
        "${(await getExternalStorageDirectory())?.path}/foreground_task_logs");
    if (!directory.existsSync()) {
      if (forCreate) {
        directory.createSync();
      } else {
        throw Exception('Directory Not Created');
      }
    }
    final String fileName =
        "${directory.path}/${DateFormat("dd-MM-yyyy").format(date)}.txt";
    print("File Path = $fileName");
    File outputFile = File(fileName);
    print("File Exists = ${outputFile.existsSync()}");
    if (!outputFile.existsSync()) {
      if (forCreate) {
        outputFile.createSync();
      } else {
        throw Exception("File Not Created");
      }
    }

    return outputFile;
  }

  Future<Logger> getLogger() async {
    try {
      return Logger(
          printer: PrettyPrinter(
            methodCount: 0,
            printTime: false,
            noBoxingByDefault: true,
          ),
          output: FileOutput(file: await _getFileName()));
    } catch (e) {
      throw Exception(e);
    }
  }

Combine multiple printers

I would like to be able to combine multiple printers in any variation and any length.

Example:

You want to prefix your log messages with the log level:
PrefixPrinterPrettyPrinter

Which could then produce this:

┌──────────────────────────────────────────────
│ 15:20:17.587 (+0:00:00.202000)
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ 🐛 DEBUG: Test message
└──────────────────────────────────────────────

Or you want to prefix every line:
PrettyPrinterPrefixPrinter

DEBUG: ┌──────────────────────────────────────────────
DEBUG: │ 15:20:17.587 (+0:00:00.202000)
DEBUG: ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
DEBUG: │ 🐛 Test message
DEBUG: └──────────────────────────────────────────────

and so on...

Current blockers:

  • Printers take a LogEvent and return a List<String>.

Maybe we should rethink the approach of using List<String>.

why any level print has stackTrace ?

code

  print("start... ");
  final logger = Logger(
    printer: PrettyPrinter(), // Use the PrettyPrinter to format and print log
  );
  logger.v("Verbose log");

  logger.d("Debug log");

  logger.i("Info log");

  logger.w("Warning log");

  logger.e("Error log");

  logger.wtf("What a terrible failure log");

out

│ #0   main (file:///D:/project/dart//bin/.dart:18:10)
│ #1   _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ 🐛 Debug log
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ #0   main (file:///D:/project/dart//bin/.dart:20:10)
│ #1   _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ 💡 Info log
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ #0   main (file:///D:/project/dart//bin/.dart:22:10)
│ #1   _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ⚠️ Warning log
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ #0   main (file:///D:/project/dart//bin/.dart:24:10)
│ #1   _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ⛔ Error log
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ #0   main (file:///D:/project/dart//bin/.dart:26:10)
│ #1   _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ 👾 What a terrible failure log
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

no file output when exit() is reached

When executing a multiWriter as part of a try catch if I have the program run an exit() as part of the error handling I get no output into a file if I comment out the exit it will write to the file as expected however execution will continue which in the case of a config file I don't want to happen... I'm not sure if I'm doing something wrong or if there is something else at play here.

Write errors higher than a specific level to crashlytics

In our apps, we are catching lots of exceptions but in some cases, it would be good to have them reported back to us.
I am currently integrating crashlytics into it.

I made a CrashlyticsLogPrinter that along with a few extra changes can work but I would still be returning an empty list.
Please suggest alternatives to this approch.
I am thinking that a custom LogOutput might help but it works on a line by line basis, I am not sure how I can use it to write a proper log on crashlytics.

Any advice will be deeply appreciated

import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:logger/logger.dart';

class CrashlyticsLogPrinter extends LogPrinter {
  final String _className;
  final FirebaseCrashlytics? _firebaseCrashlytics;

  KodomamoCrashlyticsLogPrinter(this._className, this._firebaseCrashlytics);

  @override
  List<String> log(LogEvent event) {
    /// This sends logs of warning level and above to Crashlytics
    if (event.level.index >= Level.warning.index) {
      _firebaseCrashlytics!.recordError(
        event.message,
        event.stackTrace,
        fatal: true,
        information: [_className, event.level],
        printDetails: false,
      );
    }
    return [];
  }
}

Run handlers without showing the log

Hello, Folks.

In some cases it would be interesting to run the registered handlers even without needing to show the log. This line block all handlers execution.

Would it be possible to make a change in this regard?

Tanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.