Code Monkey home page Code Monkey logo

ioniclogfileappender's Introduction

ionicLogFileAppender

Simple log file appender for Ionic 3.

  • Creates rolling log files date-stamped up to a specified max size.
  • Optionally logs to console.
  • Only writes log files if running on a Cordova platform (not in the browser)

Installation

npm install --save ionic-log-file-appender

Dependencies

Ionic Native File:

https://ionicframework.com/docs/native/file/

Configuration

Logging configuration is specified by passing a ILogProviderConfig object into the init function of the LogProvider.

{
  // If true, logs verbose details of file logging operations to console
  enableMetaLogging: boolean;

  // If true, all file log messages also appear in the console
  logToConsole: boolean;

  // Date format used in log statements
  logDateFormat: string;

  // Date format used in log file names.
  // NOTE: be careful with special characters like ':' as this can cause file system issues
  fileDateFormat: string;

  // Maximum number of log statements before file rollover
  fileMaxLines: number;

  // If the last log file exceeds this size on initialization, a new log file will be created
  fileMaxSize: number;

  // If the total size of all log files exceeds this size on initialisation, oldest files will be removed
  totalLogSize: number;

  // Name of directory to create for logs, within application's data directory
  logDir: string;

  // Prefix for log files
  logPrefix: string;

  // Developer-level logging will appear in log files if true
  devMode: boolean;
  
  // Name of directory in which to create log directory
  baseDir: string;
}

Any values not specified in the passed-in value will be set to the defaults below:

{
  enableMetaLogging: false,
  logToConsole: false,
  logDateFormat: 'yyyy-MM-dd HH:mm:ss.SSS',
  fileDateFormat: 'yyyy-MM-dd_HH-mm-ss-SSS',
  fileMaxLines: 2000,
  fileMaxSize: 1000000,
  totalLogSize: 5000000,
  logDir: 'logs',
  logPrefix: 'log',
  devMode: false,
  baseDir: <dataDirectory>
}

where dataDirectory is defined by the Ionic File plugin.

Reference in Application module

import {File} from '@ionic-native/file';
import {Platform} from 'ionic-angular';
import {DatePipe} from '@angular/common';
import {LogProvider, LogFileAppenderModule} from 'ionic-log-file-appender';

...


@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    ...
    LogFileAppenderModule.forRoot(),
    ...
  ]
  
  
  ...
  
  providers: [
      ...
      File,
      DatePipe,
      LogProvider,
      ...
  ]
})
export class AppModule { }

Initialisation in application component

  platform.ready().then(() => {
    return log.init({
      /* Your config here */
    });
  });

Usage in a class via dependency injection

export class SomeClass {
  constructor(private log: LogProvider) {
  }
  
  doSomething() {
    this.log.log('Something has been done!');
    this.log.logDev('Something has been done, but will only be logged in if devMode is true');
    const errorObj = {message: 'FooBar error', code: 128};
    this.log.err('Something unexpected happened and the error object will be printed', errorObj);
    this.log.err('Something unexpected happened and the error object will not be printed');
  }
  
  getTheLogs() {
    this.log.getLogFiles()
          .then((files: Entry[]) => {
            // Do something with the files!
          })
          .catch(err => {
            // Oops, there was an error!
          });
  }
}

ioniclogfileappender's People

Contributors

y-a-n-n avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ioniclogfileappender's Issues

change default log directory

Hi there,
According to the console output I was able to configure and generate logs by using your plugin but I can't access the files since they are being created in DataDirectoty which points to file:///data/user/0/com.mycompany.myapp/files/ and needs root permission.

Is there anyway to change the path (by configuration) so it works using externalDataDirectory (file:///storage/emulated/0/com.mycompany.myapp/files/) instead?

Providers creation failed in app.module

Hello,

I have followed your README, everything is fine at compilation time but when starting the app it seems that the logProviders could not be created : see error below

Unhandled Promise rejection: Cannot read property 'Ionic' of undefined ; Zone: ; Task: Promise.then ; Value: TypeError: Cannot read property 'Ionic' of undefined
at setupConfig (vendor.js:22437)
at callFactory (vendor.js:11002)
at createProviderInstance$1 (vendor.js:10952)
at initNgModule (vendor.js:10902)
at new NgModuleRef
(vendor.js:12145)
at Object.createNgModuleRef (vendor.js:12135)
at NgModuleFactory
.create (vendor.js:15569)
at vendor.js:5721
at t.invoke (polyfills.js:3)
at Object.onInvoke (vendor.js:4980) TypeError: Cannot read property 'Ionic' of undefined
at setupConfig (file:///android_asset/www/build/vendor.js:22437:23)
at callFactory (file:///android_asset/www/build/vendor.js:11002:20)
at createProviderInstance$1 (file:///android_asset/www/build/vendor.js:10952:26)
at initNgModule (file:///android_asset/www/build/vendor.js:10902:28)
at new NgModuleRef
(file:///android_asset/www/build/vendor.js:12145:9)
at Object.createNgModuleRef (file:///android_asset/www/build/vendor.js:12135:12)
at NgModuleFactory
.create (file:///android_asset/www/build/vendor.js:15569:25)
at file:///android_asset/www/build/vendor.js:5721:78
at t.invoke (file:///android_asset/www/build/polyfills.js:3:14976)
at Object.onInvoke (file:///android_asset/www/build/vendor.js:4980:33)

Thank for your help

Can't resolve all parameters for LogProvider

I integrated the plugin to my project. But when I am building it, it throws following error message:

Uncaught Error: Can't resolve all parameters for LogProvider: ([object Object], [object Object], [object Object], ?). at syntaxError (vendor.js:108172) at CompileMetadataResolver._getDependenciesMetadata (vendor.js:124725) at CompileMetadataResolver._getTypeMetadata (vendor.js:124618) at CompileMetadataResolver._getInjectableTypeMetadata (vendor.js:124840) at CompileMetadataResolver.getProviderMetadata (vendor.js:124849) at vendor.js:124787 at Array.forEach (<anonymous>) at CompileMetadataResolver._getProvidersMetadata (vendor.js:124747) at CompileMetadataResolver.getNgModuleMetadata (vendor.js:124466) at JitCompiler._loadModules (vendor.js:131750)

I am using Ionic Version 4.12.0.

[BUG] removeFile() function does not work

Plugin version: 2.0.7
OS: Android 9 (Real device, and emulator)

Description
When there are many log files, the log files are not automatically removed.
The following error is written to the log file

SEVERE ERROR: could not clean up old files. [object Object]

This is because removeFile() always fails

Expected behaviour
Old log files are deleted as expected.

Detail
Upon investigating the code, I suspect the filePath used is invalid.

   private removeFile(entry: Entry): Promise<any> {
        this.debug_metaLog('Removing file: ' + entry.fullPath);
        const fullPath = entry.fullPath;
        const path = fullPath.replace(entry.name, '');   // THIS IS THE PROBLEM
        return this.file.removeFile(this.config.baseDir + path, entry.name);
    }

I believe the fix should be to use the log directory

  const path = this.config.logDir;

New log file is not generated when fileMaxLines is reached

There is my ini conf :
this.logger.init({logDateFormat: 'dd-MM-yyyy HH:mm:ss.SSS', logToConsole: true, logPrefix: 'xlcomptage', fileDateFormat: 'yyyy-MM-dd'})

So, Iย use the default value fileMaxLines: 2000

My file reached 4293 lines and no other file has been created ...

Error: Can't resolve all parameters for LogProvider: (?, [object Object], [object Object])

I am still getting the same error message: Error: Can't resolve all parameters for LogProvider: (?, [object Object], [object Object])

I am having same issue.
Just added to my app.module

import {DatePipe} from '@angular/common';
import {LogProvider, LogFileAppenderModule} from 'ionic-log-file-appender';

providers
File,
DatePipe,
LogProvider

Then on app.components
constructor( private log: LogProvider...

return log.init({
/* Your config here */
});

Just did ionic serve and was getting this error

Do I need to pass a config to the Init?

Please provide an example
Also looks like npm install does not install the latest version

Plugin don't do the rollover on 'fileMaxLines'

Hi it's me again :)

I am trying to force the plugin to rollover the file according only to the number of lines.

So here is my plugin config :

 {
        enableMetaLogging: false,
        logToConsole: true,
        logDateFormat: 'yyyy-MM-dd HH:mm:ss.SSS',
        fileDateFormat: 'yyyy-MM-dd_HH-mm-ss-SSS',
        fileMaxLines: 50, // I want one and only log file  
        fileMaxSize: 100000000000,//extreme size in order to rollover only according to fileMaxLines 
        totalLogSize: 500000000000,//extreme size in order to rollover only according to fileMaxLines 
        logDir: 'Logs',
        logPrefix: 'log',
        devMode: false
    }

I can see that the size of the log file keeps increasing accordingly to what I log into but I never seen the rollover (my log's file is a lot more than 50 lines... Or is fileMaxLines not the number of lines but the number of call to the log function ? )

Thank for your help !

Dependicies and

Hello,
today i've added your package to my ionic 3 app.

With npm i am getting dependencie errors:
npm WARN @angular/[email protected] requires a peer of @angular/[email protected] bu t none is installed. You must install peer dependencies yourself. npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself. npm WARN @angular/[email protected] requires a peer of @angular/core@ 5.0.3 but none is installed. You must install peer dependencies yourself. npm WARN @angular/[email protected] requires a peer of @angular/commo [email protected] but none is installed. You must install peer dependencies yourself. npm WARN @angular/[email protected] requires a peer of @angular/compi [email protected] but none is installed. You must install peer dependencies yourself.

Within app.module.ts i am getting a build error
`Argument of type 'Platform' is not assignable to parameter of type 'Platform'. Types have separate declarations of a private property '_win'.

  L47:    return new LogProvider(file, platform, datePipe, new LogProviderConf

ig({/your config here/}));
`

Do you have any advices?

Regards
.nowrap

Null Injector Error

Hi! I'm getting null injector error after updating the imports of "ionic-angular" and "@ionic-native/file" to "@ionic/angular" and "@ionic-native/file/ngx" respectively. I'm using Ionic 5 btw.

My error is :
ERROR NullInjectorError: R3InjectorError(AppModule)[LogProvider -> [object Object] -> [object Object] -> [object Object]]:
NullInjectorError: No provider for [object Object]!

Help please ๐Ÿ˜ฟ

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.