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

Related tags

Templates logger
Overview

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.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");

To show only specific log levels, you can set:

Logger.level = Level.warning;

This hides all verbose, 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
    printTime: false // Should each log print contain a timestamp
  ),
);

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. 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 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, 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 achieved 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.

logger_flutter extension

The logger_flutter package is an extension for logger. You can add it to any Flutter app. Just shake the phone to show the console.

MIT License

Copyright (c) 2019 Simon Leier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Comments
  • when flutter is run on browser , it has lot of extra stack trace strings which get printed everytime.

    when flutter is run on browser , it has lot of extra stack trace strings which get printed everytime.

    Right now , on flutter web , it gives error saying :

    │ package:dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 248:20  get current
    js_primitives.dart:32 │ package:logger/src/printers/pretty_printer.dart 89:53                                 log
    js_primitives.dart:32 │ package:logger/src/logger.dart 124:29                                                 log
    js_primitives.dart:32 │ package:logger/src/logger.dart 85:5                                                   d
    js_primitives.dart:32 │ package:core/common_modules/logger.dart 26:63                                         d
    js_primitives.dart:32 │ package:dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 47:50            onValue
    js_primitives.dart:32 │ package:dart-sdk/lib/async/zone.dart 1381:54                                          runUnary
    js_primitives.dart:32 │ package:dart-sdk/lib/async/future_impl.dart 140:18                                    handleValue
    js_primitives.dart:32 │ package:dart-sdk/lib/async/future_impl.dart 682:44                                    handleValueCallback
    js_primitives.dart:32 │ package:dart-sdk/lib/async/future_impl.dart 711:32                                    _propagateToListeners
    js_primitives.dart:32 │ package:dart-sdk/lib/async/future_impl.dart 526:5                                     [_completeWithValue]
    js_primitives.dart:32 │ package:dart-sdk/lib/async/future_impl.dart 556:7                                     callback
    js_primitives.dart:32 │ package:dart-sdk/lib/async/schedule_microtask.dart 43:11                              _microtaskLoop
    js_primitives.dart:32 │ package:dart-sdk/lib/async/schedule_microtask.dart 52:5                               _startMicrotaskLoop
    js_primitives.dart:32 │ package:dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 168:15           <fn>
    

    For every log its giving these errors. Please let us know of any workaround for this ....

    opened by nateshmbhat 13
  • v0.9.2

    v0.9.2

    • New MultiOutput: allow multiple simultaneous outputs.
    • New AsyncOutput: performs output in asynchronous mode.
    • New LogPlatform: identifies the runtime platform, and it's capabilities.
    • New LoggerFactory: A Logger factory with predefined properties.
    • ConsoleOutput: now merging multiple lines to one String to avoid multiple IO calls.
    • MemoryOutput: overrides [] operator for events buffer access.
    • SimplePrinter, PrettyPrinter, PrefixPrinter: added optional name property.
    • Logger.log(): try catch while sending events to output,
      to avoid Logger influence over the main software.
    • README.md: fixed and improved badges.
    opened by gmpassos 10
  • Enabling Sound Null Safety

    Enabling Sound Null Safety

    As mentioned in #72 here is my PR. It's probably best to keep this on a separate branch on your end until null safety hits a stable release but I am not sure how to handle that so that's up to you.

    You will probably have to change the google/dart container to use the dev tag in order for the checks to work

    opened by DevNico 6
  • Support passing functions in the default logger implementations

    Support passing functions in the default logger implementations

    Some of our logger statements involve expensive computations like formatting objects to make the logs easy to read. To work around this, we are passing functions for the expensive log statements and they are getting evaluated in the printer right before they need to be printed.

    For example:

        logger.d(() =>
            'SEND ref=$ref topic=$topic event=$event payload=' +
            summarizeGqlPayload(payload).toString());
    

    summarizeGqlPayload in this case is relatively expensive and something we wouldn't want to be execute in production. Or at least all these little things add up to increased CPU usage. Hence we are passing a function.

    Our corresponding stringify in our custom logger looks something like this to handle functions.

      String stringifyMessage(dynamic message) {
        final finalMessage = message is Function ? message() : message;
        if (finalMessage is Map) {
          return _encoder.convert(finalMessage);
        } else if (finalMessage is Iterable) {
          return _encoder.convert(finalMessage);
        } else {
          return finalMessage.toString();
        }
      }
    

    Is this worth having as a default for the logger?

    opened by venkatd 5
  • do you maintain logger_flutter?

    do you maintain logger_flutter?

    Readme guides readers to use logger_flutter, but the package has not been maintained. logger_flutter even requires the logger version ">=0.7.0", which is outdated. (Though there's a PR for this specific issue)

    Screenshot from 2021-10-05 22-02-12

    opened by jjangga0214 4
  • Fix the import issue for FileOutput class for mobile projects

    Fix the import issue for FileOutput class for mobile projects

    • Use dart.io condition to fix the import for mobile flutter apps.

    Seems like dart.library.io is an old example from Flutter team and is not working. if (dart.io) condition works and properly imports the file for mobile apps

    opened by HiDaN4 4
  • Hybrid and Prefix Printer

    Hybrid and Prefix Printer

    Hi - new to Flutter/Dart but this has been a helpful package. This pull request would add two LogPrinter decorators.

    1. PrefixPrinter in prefix_printer.dart This allows you to wrap any logger with a prefix to all of it's logs. Inspiration for this being #2 and the AndroidStudio grep-console plugin. But this could also be used just in general to decorate any logger:
    final logger = Logger(
      printer:  PrefixPrinter(PrettyPrinter())
    );
    

    for example would add prefixes ("DEBUG", "INFO", etc.) to each line in the PrettyPrinter output. But since it is a decorator you could use the same thing for any other printer.

    It also has optional params for each log level to specify the prefix:

    PrefixPrinter(SimplePrinter(), debug: "DBUG", error: "OOPS");
    

    Light unit tests in prefix_printer_test.dart


    1. HybridPrinter in hybrid_printer.dart This allows you to use a different printer for specific log levels. Inspiration for this is that I found with my logs if they were debug logs, I just wanted a simple one-line view of the log, and with regular logs the full PrettyPrinter log. With the HybridPrinter you can accomplish that like:
    final logger = Logger(
      printer:  HybridPrinter(PrettyPrinter(), debug: SimplePrinter()),
      level: config.logLevel
    );
    

    Same thing as above where there are parameters for each level.

    Light unit tests in hybrid_printer_test.dart


    So, just for fun, using them together (how I currently am):

    final logger = Logger(
      printer:  PrefixPrinter(
          HybridPrinter(
              PrettyPrinter(
                methodCount: 2,
                colors: false,
                printTime: true
              ),
            debug: SimplePrinter()
          )),//OneLinePrinter(),
      level: config.logLevel
    );
    

    image

    The workaround for #2 thus becomes turning colors off, and using prefixes you want for the grep console plugin. Not a full fix, but works nicely for me!


    Thought I'd submit this MR in hopes you wanted to add it to the project (also wasn't sure to submit it to master or another branch). Project is awesome! I think these could help with more flexibility in people's own loggers. In general, I would be happy to contribute.

    Cheers,

    Tim

    opened by tkutcher 4
  • Always output log in console

    Always output log in console

    I added a logger dependency to a project and every time I start it will print the previously generated log after "Running Gradle task 'assembleDebug' ...". Even after I create a new flutter project, the log will still be printed.

    question 
    opened by lesliechueng1996 4
  • Updated the library to follow good practices on library organization, added compatibility with browser

    Updated the library to follow good practices on library organization, added compatibility with browser

    Hi! Newbie here.

    First of all, thank you for your awesome projects.

    Trying to use your project on a webapp, I've seen that it is incompatible with browser projects. The reason is the file file_output.dart being dependant on the library dart:io. In this pull request I've added file_output.dart as a conditional export.

    More info Sass example of conditional export

    Also, I've updated the project to follow the advice on the official docs on creating libraries:

    Note: You may have heard of the part directive, which allows you to split a library into multiple Dart files. We recommend that you avoid using part and create mini libraries instead.

    I've followed the sass project as example.

    Sorry if something is wrong and thank you for your work.

    opened by marcgraub 4
  • Support Stacktrace filters

    Support Stacktrace filters

    Description:

    If you wrap the logger in a custom logger file, the first line of the stack trace is your wrapper class (and it's not useful).

    So if you have this:

    import 'package:logger/logger.dart' as dart_log;
    
    abstract class Logger {
      static final dart_log.Logger _instance = dart_log.Logger(
        printer: dart_log.PrettyPrinter(),
      );
    
      static void v(dynamic message, [dynamic error, StackTrace? stackTrace]) =>
          _instance.log(dart_log.Level.verbose, message, error, stackTrace);
    
      static void d(dynamic message, [dynamic error, StackTrace? stackTrace]) =>
          _instance.log(dart_log.Level.debug, message, error, stackTrace);
    
    

    Then you call Logger.d(), the first stacktrace entry logger is not useful.

    To solve that, I added a stacktraceFilters, which enables you to define custom filters. So, now you can do something like:

      static final dart_log.Logger _instance = dart_log.Logger(
        printer: dart_log.PrettyPrinter(
          stacktraceFilters: [
            RegExp(r'^(packages/.*/core/source/common/logger.dart).*')
          ],
        ),
      );
    
    opened by mirland 3
  • PrefixPrinter and HybridPrinter missing

    PrefixPrinter and HybridPrinter missing

    Hey there :) I don't know if i missed somthing but unfortunately the PrefixPrinter and the HybridPrinter are note available if you download logger Version 0.9.1. Too bad, because I really like the logger 😄

    image

    Failing: PrefixPrinter and HybridPrinter are not available Steps to reproduce: Add following to your pubspec. yaml: logger: ^0.9.1 What should happen?: The PrefixPrinter and HybridPrinter should be available for usage.

    Thank you very much!

    opened by kiesman99 3
Owner
Simon Leier
Electrical engineer, Android & Flutter developer
Simon Leier
Powerful, helpfull, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server with boilerplate code free.

flutter_axelor_sdk Powerful, helpful, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server w

Abd al-Rahman al-Ktefane 5 Dec 25, 2022
A flutter package that developers have pretty logs instead just printing everything like a newbie

A flutter package that developers have pretty logs instead just printing everything like a newbie. Features Makes it easy to log to console without us

null 2 Nov 28, 2021
Unofficial wrapper for using Rapid7 insightOps logs (former LogEntries) with Dart.

An unofficial wrapper for using Rapid7 insightOps logs (former LogEntries) with Dart. This package is using logging package to do the actual logging,

Kirill Bubochkin 2 Mar 3, 2021
Do you need logs? Lumberdash is the answer!

lumberdash Do you need logs? Lumberdash is the answer! With a simple but powerful logging API, Lumberdash is the easiest way to record logs. And if th

BMW Tech 160 Dec 12, 2022
A new flutter package project which contains lots of beautiful alert dialog that will help you lot to create beautiful awesome alert box very quickly and easily.

A new flutter package project which contains lots of beautiful alert dialog that will help you lot to create beautiful awesome alert box very quickly and easily.

Karan Soni 8 Jan 8, 2022
A flutter widget to indicate loading progress. Easy to use, easy to extend

?? ?? ?? A flutter widget to indicate loading progress. Easy to use, easy to extend

Manuel Duarte 2 May 30, 2022
A TabBarController that is easy to use for flutter developers. 🥰 It supports various styles of page navigation, and you can also use it to customize your favorite styles. 🍻🍻

easy_tab_controller A user-friendly TabBarController widget for flutter developer. Getting Started This project is a starting point for a Flutter plug

圆号本昊 3 May 26, 2022
Easy to use text widget for Flutter apps, which converts inlined urls into working, clickable links

LinkText Easy to use text widget for Flutter apps, which converts inlined URLs into clickable links. Allows custom styling. Usage LinkText widget does

Aleksander Woźniak 20 Nov 4, 2022
Flutter makes it easy and fast to build beautiful apps for mobile and beyond

Flutter is Google's SDK for crafting beautiful, fast user experiences for mobile, web, and desktop from a single codebase. Flutter works with existing

Flutter 148.2k Jan 8, 2023
An app for small and medium organizations (SME) manager, with NFC-tag, e-tag and QR code features supported.

BK LAB Manager - an app for group management 1. Getting Started An app for small and medium organizations (SME) manager, with NFC-tag, e-tag and QR co

Andrew Ng 9 Dec 11, 2022
Small application where I worked with streams, firebase database, sorting, adding, modifying and deleting data.

messenger_app Small application where I worked with streams, firebase database, sorting, adding, modifying and deleting data. Features Provider: takin

Danil Shubin 2 Dec 19, 2021
Ecommerce for a small marketplace built with Flutter! with seller and buyer accounts.

BB Baazar A Flutter project. The application is an Ecommerce built with FLUTTER and FIREBASE using MVC architecture. Here, multiple sellers can upload

Shankar Lohar 2 Sep 25, 2022
Add beautiful animated effects & builders in Flutter, via an easy, highly customizable unified API.

Flutter Animate A performant library that makes it simple to add almost any kind of animated effect in Flutter. Pre-built effects, like fade, scale, s

Grant Skinner 352 Dec 25, 2022
flutter demo + small changes

demo3 A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is

null 0 Nov 23, 2021
👑 The lightweight design pattern for small management applications.

Store Pattern ?? The lightweight design pattern for small management applications. Features | Structure | Install | Usage | Documents | Technologies |

UITers 71 Sep 26, 2022
This is a set of small projects focused solely on the development of the graphical interface with Flutter

My Flutter Projects Flutter apps with cool design and animations Social Media Youtube Facebook Twitter Getting Started This project is a starting poin

Kevin Melendez 500 Dec 19, 2022
A small splashscreen used as intro for flutter applications easily with a lot of customizations ❤️🥳

Splash Screen A splashscreen package to be used for an intro for any flutter application easily with a lot of customization Currently Supported by awe

DPLYR 283 Dec 30, 2022