log_4_dart_2 0.4.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 80

Log 4 Dart 2 #

A dart package for advanced logging, with multiple and configurable appenders.

Table of Contents #

  1. Preamble
  2. Install
  3. Import
  4. Usage
  5. Appender And Configuration
  6. Changelog
  7. Copyright And License

Preamble #

The package is under construction and still needs some tweeks and code improvements!

Install #

pubspec.yaml #

Update pubspec.yaml and add the following line to your dependencies.

dependencies:
  log_for_dart_2: ^0.4.0

Import #

Import the package with :

import 'package:log_4_dart_2/log_4_dart_2.dart';

Usage #

Setup Logger #

There are two ways to setup the Logger.

  1. Store the logger configuration in seperate json file and pass the full name of the file to the initFromFile() method.
  2. Create a Map<String,dynamic> that holds the configuration and pass it to the init() method.
void main(List<String> arguments){
  // Init the logger from a configuration file
  Logger().initFromFile('/path/to/log4d.json');
  // Or by using a Map<String,dynamic>
  Logger().init(config);
}

Take a look at Example Configuration for a full example.

Logging #

The Logger offers multiple methods for logging on different levels.

static String TAG = 'TestClass';
Logger().debug(TAG, 'Lorem Ipsum');
Logger().trace(TAG, 'Lorem Ipsum');
Logger().info(TAG, 'Lorem Ipsum');
Logger().warning(TAG, 'Lorem Ipsum');
Logger().error(TAG, 'Lorem Ipsum');
Logger().fatal(TAG, 'Lorem Ipsum');

Appender And Configuration #

ConsoleAppender #

The ConsoleAppender is a simple appender that appends every log entry to the console output.

  • type = The type of the appender. This has to be set to CONSOLE.
  • dateFormat = The date format used for the appender. Default = yyyy-MM-dd HH:mm:ss.
  • level = The loglevel for this appender.
  • format = The format for the log output. See Log format for more information.

FileAppender #

The FileAppender appends every log entry to a logfile.

  • type = The type of the appender. This has to be set to FILE.
  • level = The loglevel for this appender.
  • format = The format for the log output. See Log format for more information
  • dateFormat = The date format used for the appender. Default = yyyy-MM-dd HH:mm:ss.
  • filePattern = The pattern used for the filename.
  • fileExtension = The fileextension. Default is "log".
  • path = The path to the file
  • rotationCycle = The rotation cycle for the appender. See Rotation Cycle. Default ist NEVER.

Note: If a path was specified, it must also exist!

HttpAppender #

The HttpAppender sends a log entry via HTTP POST request to a given url.

  • type = The type of the appender. This has to be set to HTTP.
  • dateFormat = The date format used for the appender. Default = yyyy-MM-dd HH:mm:ss.
  • level = The loglevel for this appender.
  • url = The url for the POST request.
  • headers = A list of headers where the name and value of the header a seperated by a ":". Example "Content-Type:application/json"

EmailAppender #

The EmailAppender sends a log entry via email to a given address.

  • type = The type of the appender. This has to be set to EMAIL.
  • dateFormat = The date format used for the appender. Default = yyyy-MM-dd HH:mm:ss.
  • level = The loglevel for this appender.
  • host = The smtp server.
  • user = The user for this server.
  • password = The password for the given user.
  • port = The port of the smtp server
  • fromMail = The sender email. As a default, the username is used.
  • fromName = The sender name.
  • to = A list of email addresses to send the email to.
  • toCC = A list of email addresses to receive a copy.
  • toBCC = A list of email addresses to receive a blind copy.
  • ssl = Whether to use ssl or not.
  • templateFile = Full path to a file containing the template to use to send via email. If no template is given the appender will send the LogRecord as JSON. You can use the same placeholders within your template that are used for the format setting. See Log format for more information.
  • html = Whether the given template is plaintext or html. Default is false.

Note: Due to the mailer package that is used to provide this appender, this works only for mail servers that need authorization by user/password.

MySqlAppender #

The MySqlAppender appends every log entry to a table in a mysql database.

  • type = The type of the appender. This has to be set to MYSQL.
  • level = The loglevel for this appender.
  • host = The host for the mysql database.
  • user = The user.
  • password = The password of the user.
  • port = The port of the host.
  • database = The database name.
  • table = The table to write to.

Create the table with the given statement. Replace $table with your desired table name.

CREATE TABLE `$table` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `tag` VARCHAR(45) NULL,
  `level` VARCHAR(45) NULL,
  `message` VARCHAR(45) NULL,
  `time` VARCHAR(45) NULL,
  PRIMARY KEY (`id`));

Adding Custom Appender #

Log4Dart2 supports the usage of custom appenders. Create a class that extends the Appender and implements the append and init methods.

import 'package:log_4_dart_2/log_4_dart_2.dart';

class CustomAppender extends Appender {
  @override
  void append(LogRecord logRecord) {
    // TODO: implement append
  }

  @override
  void init(Map<String, dynamic> config, bool test, DateTime date) {
    // TODO: implement init.
  }

  @override
  Appender getInstance(){
    return CustomAppender();
  }

  @override
  String getType(){
    return 'CustomAppender';
  }
}

Register the custom appender in the Logger via the registerAppender() method before the logger is initialized.

Logger().registerAppender(CustomAppender());

Log Format #

The format of the log entrys can be configured for some appender.

  • %d = The date.
  • %i = The identifier.
  • %t = The tag.
  • %l = The log level.
  • %m = The message.

Examples :

  • "%d %i %t %l %m"
  • "This log entry was created on %d from class %t from thread %i. It has the level %l and the message %m"

Example for an html template :

<h1>Log Event</h1>
<p>Message: %m</p>
<p>Class: %t</p>
<p>Time: %d</p>
<p>Level: %l</p>

Rotation Cycle #

The rotation cycle can be configured for some appender. It defines how offen a new file is created to store the logging data.

  • NEVER (Never rotate)
  • DAY (Rotate on a daily basis)
  • WEEK (Rotate on weekly basis)
  • MONTH (Rotate on monthly basis every first day of the month)
  • YEAR (Rotate on a yearly basis every first day of the year)

Example Configuration #

Some configuration examples with all possible appenders and their settings.

var config = {
  'appenders': [
    {
      'type': 'CONSOLE',
      'dateFormat' : 'yyyy-MM-dd HH:mm:ss',
      'format': '%d %i %t %l %m',
      'level': 'INFO'
    },
    {
      'type': 'FILE',
      'dateFormat' : 'yyyy-MM-dd HH:mm:ss',
      'format': '%d %i %t %l %m',
      'level': 'INFO',
      'filePattern': 'log4dart2_log',
      'fileExtension': 'txt',
      'path': '/path/to/'
      'rotationCycle': 'MONTH'
    },
    {
      'type': 'EMAIL',
      'dateFormat' : 'yyyy-MM-dd HH:mm:ss',
      'level': 'INFO',
      'host': 'smtp.test.de',
      'user': 'test@test.de',
      'password': 'test',
      'port': 1,
      'fromMail': 'test@test.de',
      'fromName': 'Jon Doe',
      'to': [
        'test1@example.com',
        'test2@example.com'
      ],
      'toCC': [
        'test1@example.com',
        'test2@example.com'
      ],
      'toBCC': [
        'test1@example.com',
        'test2@example.com'
      ],
      'ssl': true,
      'templateFile': '/path/to/template.txt',
      'html': false
    },
    {
      'type': 'HTTP',
      'dateFormat' : 'yyyy-MM-dd HH:mm:ss',
      'level': 'INFO',
      'url': 'api.example.com',
      'headers': [
        'Content-Type:application/json'
      ]
    },
    {
      'type': 'MYSQL',
      'level': 'INFO',
      'host': 'database.example.com',
      'user': 'root',
      'password': 'test',
      'port': 1,
      'database': 'mydatabase',
      'table' : 'log_entries'
    }
  ]
};
{
  "appenders": [
    {
      "type": "CONSOLE",
      "dateFormat" : "yyyy-MM-dd HH:mm:ss",
      "format": "%d %i %t %l %m",
      "level": "INFO"
    },
    {
      "type": "FILE",
      "dateFormat" : "yyyy-MM-dd HH:mm:ss",
      "format": "%d %i %t %l %m",
      "level": "INFO",
      "filePattern": "log4dart2_log",
      "fileExtension": "txt",
      "path": "/path/to/",
      "rotationCycle": "MONTH"
    },
    {
      "type": "EMAIL",
      "dateFormat" : "yyyy-MM-dd HH:mm:ss",
      "level": "INFO",
      "host": "smtp.test.de",
      "user": "test@test.de",
      "password": "test",
      "port": 1,
      "fromMail": "test@test.de",
      "fromName": "Jon Doe",
      "to": [
        "test1@example.com",
        "test2@example.com"
      ],
      "toCC": [
        "test1@example.com",
        "test2@example.com"
      ],
      "toBCC": [
        "test1@example.com",
        "test2@example.com"
      ],
      "ssl": true,
      "templateFile": "/path/to/template.txt",
      "html": false
    },
    {
      "type": "HTTP",
      "dateFormat" : "yyyy-MM-dd HH:mm:ss",
      "level": "INFO",
      "url": "api.example.com",
      "headers": [
        "Content-Type:application/json"
      ]
    },
    {
      "type": "MYSQL",
      "level": "INFO",
      "host": "database.example.com",
      "user": "root",
      "password": "test",
      "port": 1,
      "database": "mydatabase",
      "table" : "log_entries"
    }
  ]
}

Changelog #

For a detailed changelog, see the CHANGELOG.md file

MIT License

Copyright (c) 2020 Ephenodrom

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.

Changelog #

0.4.0 - 2020-01-14 #

  • Add template feature to EmailAppender (#4)
  • Add unit tests

0.3.3 - 2020-01-13 #

  • Update dependencies

0.3.2 - 2020-01-10 #

  • Improve type safety

0.3.1 - 2020-01-07 #

  • Improve initialization of the logger

0.3.0 - 2020-01-07 #

  • Add unique identifier to log format (#3)
  • Add custom dateformat for appender (#2)
  • Simplify use of custom appenders. (#5)

0.2.1 - 2020-01-03 #

  • Improve documentation

0.2.0 - 2020-01-02 #

  • Add rotation cycle to the FileAppender
  • Add custom appender feature
  • Add unit tests

0.1.0 - 2019-12-21 #

  • Initial release

example/main.dart

import 'package:log_4_dart_2/log_4_dart_2.dart';

void main() {
  var config = {
    'appenders': [
      {'type': 'CONSOLE', 'format': '%d %t %l %m', 'level': 'INFO'},
    ]
  };
  Logger().init(config);
  ExampleClass.doSomething();
}

class ExampleClass {
  static String TAG = 'ExampleClass';

  static void doSomething() {
    Logger().info(TAG, 'I am doing something!');
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  log_4_dart_2: ^0.4.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:log_4_dart_2/log_4_dart_2.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
60
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
80
Learn more about scoring.

We analyzed this package on Mar 30, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
basic_utils ^2.4.7 2.5.3
intl ^0.16.0 0.16.1
mailer ^3.0.4 3.0.4
mysql1 ^0.17.1 0.17.1
Transitive dependencies
asn1lib 0.6.4
async 2.4.1
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.4
http 0.12.0+4
http_parser 3.1.4
json_annotation 3.0.1
logging 0.11.4
meta 1.1.8
mime 0.9.6+3
path 1.6.4
pointycastle 1.0.2
pool 1.4.0
source_span 1.7.0
stack_trace 1.9.3
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
pedantic ^1.9.0 1.9.0
test ^1.6.0