mowispace / react-native-logs Goto Github PK
View Code? Open in Web Editor NEWPerformance-aware simple logger for React-Native and Expo with namespaces, custom levels and custom transports (colored console, file writing, etc.)
License: MIT License
Performance-aware simple logger for React-Native and Expo with namespaces, custom levels and custom transports (colored console, file writing, etc.)
License: MIT License
Saw this:
I think the .then()
is redundant? Or maybe it serves some purpose that's not immediately obvious to me?
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> = {
}
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.
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?
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.
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?
Great lib, thank you for your work.
Maybe we could use react-native-fs, but I just found that 3.0.0 has some issues with java exceptions. So actually I don't know how could we use the fs
module.
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.
In this section of the docs it says multiple arguments will be concatenated, but they are actually output on separate lines.
Using the example provided, the logs look like this:
Is that the intention? Or should they be concatenated on a single line?
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,
};
It occurs to me that if I send 2 log messages at the same time, there will be a race condition here:
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.
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
When transport would accept an array of functions multiple transports could be supported out of the box.
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');
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
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);
In 3.0.0 transports get already stringified message.
Add config option to disable stringify of message or add an option to provide serializer function for msg.
I know there is rawMsg, but I have problem with JSON.stringify not handling circular dependencies.
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?
Issue: My logs are not colored in VSCod. Instead, they show up with strings describing the colors:
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
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).
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:
consoleTransport
using only console.log
?mapConsoleTransport
not supporting colours.Would it be possible to merge the 2 and have it map by default and use coloured output?
I'd like to colour my loggers with a specific colour.
Would be helpful if during extend
one could specify options for each transport like:
const logger = mainLogger.extend("api", { consoleTransport: { colour: "darkgray" } })
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
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;
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.
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.
Would it be possible to support RGB colours for the console transport?
I think it should be possible with the help of https://github.com/chalk/ansi-styles
and a colour could be created like styles.color.ansi16m(100,0,0)
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 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?
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 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.
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);
#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.
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?
Current Expo/react-native-unimodules FileSystem implementation exports EncodingType
. fileAsyncTransport is looking for EncodingTypes
which results in throwing FileSystem not supported error
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
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.
I stumbled over the fileName
config setting and it seems its only set during initialisation of the transport.
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).
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.
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:
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 :)
Using string substitutions being passed to the log does not work on consoleTransport
I presume it's because you're assembling the message and sending it out as one string.
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?
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!
thx for the new release but unfortunately error loggs are now printed in a green color which doesn't indicates an error on the first look.
Screenshots shows transportOptions.color:
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
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
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?
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.
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?
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:
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! :-)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.