Giter Site home page Giter Site logo

mowispace / react-native-logs Goto Github PK

View Code? Open in Web Editor NEW
411.0 5.0 29.0 651 KB

Performance-aware simple logger for React-Native and Expo with namespaces, custom levels and custom transports (colored console, file writing, etc.)

License: MIT License

TypeScript 71.95% JavaScript 28.05%
react-native logs debugging ios android logger logging debug file custom

react-native-logs's People

Contributors

alessandro-bottamedi avatar baldur avatar chmac avatar dependabot[bot] avatar harjot1singh avatar hu-qi avatar iago-f-s-e avatar jbreuer95 avatar pke avatar timarney 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  avatar  avatar  avatar

react-native-logs's Issues

TransportOptions typings

Do you think it would be possible to improve the typings for configs so that by specifying which transport the config is the config for via template argument the transportOptions could be typed?

const config: configLoggerType<ConsoleTransportConfig> = {
}

Proposed fix to support configurations with isolateModules

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Running tsc on my project resulted in the following errors:

node_modules/react-native-logs/src/index.ts:465:3 - error TS1205: Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'.

465   transportFunctionType,
      ~~~~~~~~~~~~~~~~~~~~~

node_modules/react-native-logs/src/index.ts:466:3 - error TS1205: Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'.

466   configLoggerType,
      ~~~~~~~~~~~~~~~~


Found 2 errors.

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

For whatever reason, tsc decided to still run its checks on the react-native-logs/src folder, despite node_modules being excluded in tsconfig.json and despite any changes I made to try and get it to ignore it.

From what I gather, the two solutions were to either enable skipLibCheck (which didn't seem to help) or turning off isolateModules (which I would rather avoid).

I eventually settled on patch-package with the following patch which seems to solve my problem:

diff --git a/node_modules/react-native-logs/src/index.ts b/node_modules/react-native-logs/src/index.ts
index 59327a4..ddfde88 100644
--- a/node_modules/react-native-logs/src/index.ts
+++ b/node_modules/react-native-logs/src/index.ts
@@ -45,7 +45,7 @@ try {
 }
 
 /** Types Declaration */
-type transportFunctionType = (props: {
+export type transportFunctionType = (props: {
   msg: any;
   rawMsg: any;
   level: { severity: number; text: string };
@@ -60,7 +60,7 @@ type logMethodType = (
 ) => boolean;
 type levelLogMethodType = (...msgs: any[]) => boolean;
 type extendedLogType = { [key: string]: levelLogMethodType | any };
-type configLoggerType = {
+export type configLoggerType = {
   severity?: string;
   transport?: transportFunctionType;
   transportOptions?: any;
@@ -462,8 +462,6 @@ const logger = { createLogger };
 
 export {
   logger,
-  transportFunctionType,
-  configLoggerType,
   consoleTransport,
   fileAsyncTransport,
   sentryTransport,

I don't know if there are any hidden implications to this change (maybe specific TS version incompatibility?), so I'd love to know if there are.
But feel free to reject this suggestion if that is the case.

This issue body was partially generated by patch-package.

Suggestion: Multiple parameters on log()

Nice and simple framework... have just added it and like it already :)

I'm though missing the option for console.log where you add multiple params so you could do like:
log.error('An error occured', error);

I believe that is more readable that doing:
log.error(`An error occured ${error}`);

Would that be a feature worth adding to your nice framework?

Ansi Color Options

Should be able to select the correct color per level. Right now the color is selected based on the severity of the level. However those severity colors don't make sense once you get past 4 (red-error). If I want my error level to be 10 the color is green, which doesn't make any visual sense.

Unrecognised event output

image
I seem to be getting an "unrecognised event" line being output for every log.info I do, I can not find anything online about how to solve this, do you have any advice?

Support for common console.log multiple args

In browsers logger implementation one can write:

const bar = "bar"
logger.log("foo", bar)

which will lead to one line of text output delimited by space, between each arguments toString() call result: foo bar

This library would output 2 lines of logging at the moment.
Is it to late to change that behaviour?

Allow passing in a `console` for `consoleTransporter`

I want to avoid changing a lot of the existing code so I want to remap the console.log to your transport but because you're logging using console.log it will get as expected a stack overflow. Can you provide a way of passing a "original" console if we saved it.

Sentrytransport Error

Sentrytransport causing the below error
Error
TaskQueue: Error with task : t.options.SENTRY.captureException is not a function. (In 't.options.SENTRY.captureException(t.msg)', 't.options.SENTRY.captureException' is undefined)

App is getting crashed on open and above error is seen in Sentry.

Configuration
Expo managed workflow SDK 40
sentry expo package 4.0.1
react native loggers
Config
const config = {
severity: DEV ? "debug":"error",
transport: DEV ? consoleTransport : sentryTransport,
transportOptions: {
colors: "ansi", // custom option that color consoleTransport logs,
SENTRY: Sentry
},
levels: {
debug: 0,
info: 1,
warn: 2,
error: 3,
},
async: true,
dateFormat: "time",
printLevel: true,
printDate: true,
enabled: true,
};

Race conditions with Expo FS

It occurs to me that if I send 2 log messages at the same time, there will be a race condition here:

https://github.com/onubo/react-native-logs/blob/a49a8d341a4d1c085e1cea25e91c25841a46dfd8/src/transports/fileAsyncTransport.ts#L10-L12

If I have 2 simultaneous writes, they will both read the original file, and they'll both write each having added 1 line, and whichever write succeeds last will overwrite the first write.

I've tested this in our app like so:

    log.debug("First message #UKxKek");
    log.debug("Second message #UKxKek");
    log.debug("Third message #UKxKek");
    log.debug("Fourth message #UKxKek");

We only get the fourth message in our log files. Unfortunately this is a bit of a hard problem to solve. I'd assume that because RNFS exposes an appendFile() API that it doesn't suffer from this problem.

Global logger?

Hi, great library.

But instead of having to do in every file:

import { logger } from 'react-native-logs';

var log = logger.createLogger();
log.info('This is an Info log');

is there a way to do:

import { logger } from 'react-native-logs';

logger.info('This is an Info log');

It would be way simpler to just import the logger wherever I want instead of having to also create the logger in every file as well.
For example, loguru in python does this and it's great https://github.com/Delgan/loguru#ready-to-use-out-of-the-box-without-boilerplate

Disable method is not working for extensions

I tried to use the disable method on an extension but cannot get it to work. It just disables all logging. Could you please provide an example? Thanks!

import { logger, consoleTransport } from "react-native-logs";

const config = {
  transport: consoleTransport,
  enabledExtensions: ['ROOT','HOME']
};

var log = logger.createLogger(config);
var rootLog = log.extend('ROOT');
var homeLog = log.extend('HOME');

log.disable('HOME');
log.disable(homeLog);

rootLog.info('Magenta Extension and bright blue message');
homeLog.error('Green Extension and bright red message');

Unformatted log with iTerm or default macos terminal

When using iTerm all logs are unformatted.

%c8/19/2020, 9:48:03 PM | INFO | Unauthenticated, trying to refresh token color: dodgerblue;font-weight:bold
%c8/19/2020, 9:48:03 PM | INFO | Requesting new token via refresh token authentication color: dodgerblue;font-weight:bold

Failed to display colour in console

Hello, I am using the default example. I have also reviewed some of the previous issues about displaying colour though I have failed to view the logs in the console in colour. I am also using typescript in my project.

Below is the implementation

import { logger, consoleTransport } from "react-native-logs";

const defaultConfig = {
  severity: "debug",
  transport: consoleTransport,
  transportOptions: {
    color: "ansi", // custom option that color consoleTransport logs
  },
  levels: {
    debug: 0,
    info: 1,
    warn: 2,
    error: 3,
  },
  async: true,
  dateFormat: "time",
  printLevel: true,
  printDate: true,
  enabled: true,
};

var log = logger.createLogger(defaultConfig);

monkey patch console?

Does anything speak against monkey-patching all console logging relevant methods by say, calling a logger.install() function?

This way one would not even have to import a logger into each module but it would simply work for all code using console.info etc?

colorConsoleSync not showing colors in VSCode

Issue: My logs are not colored in VSCod. Instead, they show up with strings describing the colors:

output:
Screen Shot 2020-05-22 at 2 13 47 PM

code:


const defaultConfig = {
  severity: 'debug',
  transport: colorConsoleSync,
  // transport: customTransport,
  transportOptions: null,
  levels: {
    debug: 0,
    info: 1,
    warn: 2,
    error: 3,
  },
};

const _logger = logger.createLogger(defaultConfig);

I also get the same output when using consoleSync

Align level (and feature) names in output

It would be great if there was an option to left align messages when level printing is enabled. As it is the different lengths of level names results in jagged and hard to read output when different levels are interleaved.

(Feature printing can easily be aligned by just choosing fixed length features, but having the same for fathers would be nice too).

Colour support for mapConsoleTransport or map support for consoleTransport

I recently wrote a test and wondered why my expectation that the logger.error would call console.error eventually did not work.
Then I found out that consoleTransport uses console.log always and that to mimic console output traditionally one would have to use mapConsoleTransport

Now I have 2 questions:

  1. Why is consoleTransport using only console.log?
  2. Why isn't mapConsoleTransport not supporting colours.

Would it be possible to merge the 2 and have it map by default and use coloured output?

`any` type for dynamic log methods

Is it possible to not use any for dynamic log methods in class logTyped? Maybe these methods can be typed like this:

(...args: unknown []) => void

fileAsyncTransport() error

Hi guys!

Noticed error in fileAsyncTransport function. If I won't use 'date-today' option in fileName - log file will be always named as 'log'.

Seems like you have an error in line 93:
} else if (props?.options?.fileName) props.options.fileName;

should be changed to:
} else if (props?.options?.fileName) fileName = props.options.fileName;

Log rotate feature

Hi
i am using this log package, but i want to use log-rotate with this, which create new file on date change, is there any way how i can achieve.

No output produced after expo upgrade (to 45)

After expo upgrade (to 45) no logging appears using either console.log or a package like react-native-logs. Even explicitly enabling logging with

import { Logs } from 'expo'

Logs.enableExpoCliLogging()

produces no output.

Doesn't print line number or file name

When logging, it doesn't show the line number or file name of the log. Instead it shows this
consoleTransport.js:40
when logging.
How to print the line number and file name with this logger?

Would it make sense to remove dist from git?

Would it make sense to remove the built javascript dist folder from git? I'm used to TypeScript packages that only check the src folder into git. Maybe there's something I'm missing here?

Enable all extensions by default

Common other logging libs like log4j or slf4j allow to crate namespaced loggers too. However, they always output those loggers by default.

It would greatly increase the workflow if one would not have to manually add each namespaced logger to the config.

Instead how about treating enabledExtensions as an include list only if it exists. Otherwise all extensions are enabled by default.

We could also think about something like the well known node package debug does by enabling fine grained sub-loggers via wildcards.

Hermes Engine `dateFormat` support

Overview

Hermes currently supports toLocaleTimeString and toLocaleString on Android only. As a result, time is often the wrong timezone and the format of the date for local may be incorrect on iOS.

https://github.com/onubo/react-native-logs/blob/9dfc362ec7a18885f9ad4844f69ac63e877086e2/src/index.ts#L295-L303

Proposal

  • Add alternative implementations of these formatters AND/OR
  • Allow dateFormat to be a function so that the user can control formatting
import {format} from 'date-fns'
import { logger, consoleTransport } from "react-native-logs";

const config = {
  dateFormat: (date) => format(date, 'h:mm a')
}

const log = logger.createLogger(config);

Enable and disable config for multiple messages concatenation.

#27 is a bit related but in my use case I would like to disable the default concatenation when I pass multiple messages to the log functions. This is because I don't want my main log message to be cluttered with stringified stuff and I would like to handle my other passed messages in a custom way already.

I can still access additional objects via the rawMsg prop but my main message is still cluttered with the stringified version of it. It would be great to have this things as optional via the config.

Regards.

limit file size

if file exceeds 1mb make a new file dump new logs there and make that file name as latest if no of files exceed more than 5 delete oldest file is this possible with this library?

Expo file system not supported

Current Expo/react-native-unimodules FileSystem implementation exports EncodingType. fileAsyncTransport is looking for EncodingTypes which results in throwing FileSystem not supported error

Don't stringify objects

Hey @alessandro-bottamedi

is there a possibility to stop rn-logs to stringify passed objects to the logger?
When it's stringified, I can't expand/collapse the passed object and it's quit confusing at first glance.

Thx in advance ๐Ÿ˜„

Cheers,
(another) Alessandro

Use console.* for consoleTransport

Right now, consoleTransport prints everything to console.log. In order to use LogBox from react-native, console.warn and console.error have to be used.

Bug? When the app is running longer than a day will the log file format still be correctly named?

I stumbled over the fileName config setting and it seems its only set during initialisation of the transport.

https://github.com/onubo/react-native-logs/blob/43b4ee5e195b6a1c22c76fcfd5fb3ca433c44710/src/transports/fileAsyncTransport.ts#L58

The means if the app stars one minute before midnight it would log to the wrong file from that moment on. No new file with the correct date will be create until app-restart.

Am I reading that correctly?

If so, an easy fix would be to have fileName be a function that is called on each append (could be a perf hit though).

Filename/FilePath for rnFsFileAsync

Hey there,

What would you think about slightly changing the rnFsFileAsync so that the filename/filepath is providable and not hardcoded?

Example usage:
An App where you can login and want to log per user and not per app.

Features and improvement suggestions

Thanks for this logger. It was a missing master piece in the RN ecosystem.

Here are some improvements suggestions I would be happy to have. Idk if I will have time to do some pull request, so I let you my thought here:

  • namespacing the loggers: it let us focus on some part of the stack/app
  • namespacing children: same as above, but to look deeper.
  • context: attaching a persistent context to a logger during it's lifecycle brings helpful information when debuging
  • a firebase adapter
  • a gcp adapter

Tbh, I often use this awesome logger for isomorphic web app: https://github.com/christophehurpeau/nightingale . It brings the features mentioned above and could be a great source of inspiration.

One more time: thanks for this great package :)

Support for max file size

If I'm not mistaken, there is no support for setting the max file size of the log file.
Is there a default one, or will the file grow indefinitely?

Any reason why logType isn't exported?

I'm writing a class with its own custom logger instance and using typescript I can't make a logger instance a typed property / member of the class correctly - since logTyped isn't exported:

import RNFS from 'react-native-fs';
import { logger } from 'react-native-logs';

export default class CallLoger {
  loggerInstance: logTyped;

  constructor(props) {
    // ...
  }

  initialise(callId, userId) {
    this.loggerInstance = logger.createLogger({
       // ...
    });
  }
}

Typescript complains here - Am I using the wrong approach? I want to have a long lived class that initialises a logger which writes to a new file each time, but that is initialised several times during the app's lifecycle

Thanks!

Suggestion: Add create module logger

It would be nice to create a module logger, so the module name would be part of the log message.

I.e. you would have the base logger initialized with the configuration. From that one you would be able to create a logger for a given module. Something like const log = logger.loggerForModule('AuthModule`) and then you could do log.info('Authenticated user'); which would give you:
25/04/2020, 17:40:45 | INFO | AutheModule | Authenticated user

log.error shows empty object

Hi all ๐Ÿ‘‹

I'm facing problems when logging errors in try catch blocks.
Caught and logged errors shows only an empty object ๐Ÿ˜ž

19/01/2021, 08:23:55 | ERROR | {}

Any ideas? console.error(err) does it right:
Error: BLE_CONNECTION_ERROR: Cannot convert undefined or null to object

Send sentry logs

In my project, I create a util call log. Here is content.

import { logger, sentryTransport } from "react-native-logs"
import * as Sentry from "@sentry/react-native"

/*
 * Configure sentry
 */

const config = {
  severity: "error",
  transport: sentryTransport,
  transportOptions: {
    SENTRY: Sentry,
  },
}

export const log = logger.createLogger(config)

In my app.tsx, I import log and try my first error log but it doesn't work:

import React, { useEffect,} from "react"
import {Text, View} from "react-native"
import { log } from "./utils/log"

function App() {
  useEffect(() => {

    log.error("My first Sentry error!")
  }, [])
  return (
       <View><Text>test</Text></View>
  )
}

export default App

Can anyone help me to push my first log?

error in build

Hi.thank you for your update.
there is problem in line 21 of /react-native-logs/dist/transports/rnFsFileAsync.js file
you must define let RNFS = require('react-native-fs'); and in line 32 you must remove let befor RNFS because you must define this in line befor line 21.

How can I save log in file manager (storage) of mobile.

I want to save log file in file manager of my app.
So that I can see my log file in File Manager->android->com.appname->pathToLogFile.txt

What I have tried till now is:-

` import React from 'react';
import { logger } from 'react-native-logs';
import { consoleSync } from 'react-native-logs/dist/transports/consoleSync';
import { colorConsoleSync } from 'react-native-logs/dist/transports/colorConsoleSync';
import { colorConsoleAfterInteractions } from 'react-native-logs/dist/transports/colorConsoleAfterInteractions';
import { rnFsFileAsync } from 'react-native-logs/dist/transports/rnFsFileAsync';

 var customTransport = (msg, level, options) => {
  // Do here whatever you want with the log message
  // Eg. a console log: console.log(level.text, msg)
 };

 const log = logger.createLogger({
  transport: (msg, level, options) => {
      colorConsoleSync(msg, level, options);  
      rnFsFileAsync(msg, level, options);
      //customTransport(msg, level, options);
   },
   transportOptions: {
      hideDate: true,     //change to show date and time
     dateFormat: 'iso',   //change date format
     hideLevel: true,     //change to show level of debug
     loggerName: 'log',      //name of file in file manager as <loggerPath>/<fileName>.txt
   },
  });

  if (__DEV__) {
    log.setSeverity('debug');   //it will show log of debug, info, warn & error in development mode
  } else {
   log.setSeverity('warn');   //it will show log of warn & error only in production mode
 }

export default log;

`
How can I achieve this?

Open to making the file transport pluggable?

Firstly, thanks for this logger. I've been searching for a while for something to use in React Native, and this seems to hit a pretty sweet spot!

I'm using expo, and I prefer to avoid the RNFS filesystem package if possible. I wrote a package expo-fs to make isomorphic-git compatible with expo's filesystem. I was looking to write a custom transport for react-native-logs to do the same. Then looking at the code, I realise it's really only this one pieces that would need to be changed:

https://github.com/onubo/react-native-logs/blob/913eb01ac550970b659528ae04a80080bce85b4c/src/transports/rnFsFileAsync.ts#L44-L48

That got me to thinking, would you be open to a PR that makes this piece pluggable? I haven't thought much about how to achieve that yet, maybe turn it into a factory that takes an appendFile() function, then use that factory to generate the same transport as currently so it's fully backwards compatible, but easy enough to drop in something else in place.

Wanted to check in before I start hacking on anything, I can equally just copy that file into a separate package and write a react-native-logs-expo-fs-transport or similarly creatively named package! :-)

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.