Giter VIP home page Giter VIP logo

logger's Introduction

Effector Logger

Pretty logger for stores, events, effects and domains.

All Contributors

Chrome-DevTools-Console
Chrome-DevTools-Console-Dark

Installation

npm add effector
npm add --dev effector-logger

or yarn

yarn add effector
yarn add -D effector-logger

Note: effector-logger requires effector to be installed

Usage

Prepare metadata

To make logs more useful we need additional metadata (like names, locations in the code, etc), which is provided by one of the effector plugins.

Babel-plugin

Babel-plugin is built-in in the effector package.

Just add it to your babel configuration.

{
  "plugins": ["effector/babel-plugin"]
}

It is also useful to enable loc generation for dev environment, to see for exact locations of units in the code.

{
  "plugins": [["effector/babel-plugin", { "addLoc": true }]]
}

Read the docs

SWC Plugin

Read effector SWC plugin documentation

Start logging

Just call attachLogger in your entrypoint module.

NOTE: To "see" the createStore, createEvent, etc calls effector-logger needs to be imported at the very top of your entrypoint module. This way initial states of stores will be properly logged at the moment of attachLogger call.

Update logs are not affected by import order.

// src/index.tsx
import { attachLogger } from 'effector-logger';

import React from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './app';
import { appStarted } from './shared/app-events';

attachLogger();

appStarted();

createRoot(document.querySelector('#app')).render(<App />);

After that you will see the logs in your console.

With Scope

If your app uses scope (e.g. you have Server-Side-Rendering) - you will need to pass it to the logger to work.

attachLogger({ scope });

Updates related to provided scope will be prefixed with scope id.

Name

There optional name prefix to the logs. It can be useful if there are few instances of your app, which are using different scopes or if you just want prefix that is better than boring scope id.

attachLogger({
  scope,
  name: `my-cool-app-${appId}`, // all logs will be prefixed with this string
});

Stop logs

To stop logs just call unsubscribe function.

const unlogger = attachLogger();

unlogger();

Hide any unit from log

Sometimes it is required to hide some events or stores from log. It is simple to implement: just call configure on your unit.

import { createEvent } from 'effector';
import { configure } from 'effector-logger';
import { $data, loadDataFx } from './model';

const pageMounted = createEvent<number>();

configure(pageMounted, { log: 'disabled' });

// You can pass multiple units as array
configure([$data, loadDataFx], { log: 'disabled' });

Force any unit to be logged

By default only non-derived units are logged. If you want to force some unit to be logged, use configure enabled

import { createEvent } from 'effector';
import { configure } from 'effector-logger';
import { $data, loadDataFx } from './model';

const pageMounted = createEvent<number>();

const mappedMounted = pageMounter.map((x) => x);

configure(mappedMounted, { log: 'enabled' });

// You can pass multiple units as array
configure([$data, loadDataFx], { log: 'enabled' });

Redux DevTools support

Redux DevTools is moved to a different package.

See the @effector/redux-devtools-adapter

Contributors ✨

Thanks go to these wonderful people (emoji key):


Andrey Antropov

💻

Sergey Sova

💻

Sozonov

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Release process

  1. Check out the draft release.
  2. All PRs should have correct labels and useful titles. You can review available labels here.
  3. Update labels for PRs and titles, next manually run the release drafter action to regenerate the draft release.
  4. Review the new version and press "Publish"
  5. If required check "Create discussion for this release"

logger's People

Contributors

alexandrhoroshih avatar allcontributors[bot] avatar dependabot[bot] avatar drevoed avatar ejnshtein avatar igorkamyshev avatar ilyaagarkov avatar laiff avatar lokhmakov avatar sergeysova avatar yanlobat avatar zerobias 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

logger's Issues

Error: guard: expect clock to be a unit (store, event or effect) or array of units

Hey 👋 Not sure if I'm doing something wrong or there is actually a bug.

So I have this packages installed:

        "effector": "^21.8.11",
        "effector-react": "^21.3.2",
        "effector-logger": "^0.13.3",

And I'm using parcel v2 as a builder.

Every time I try to use anything related to effector-logger I get this error

image

I get this error either if I import bablel config or either just directly import something from 'effector-logger'.

Which other details can be useful?

Logging of mapped/combined stores

In some cases, it would be nice to have mapped/combined stores to be logged as well. Although if we will log all of the derived stores it might add noise, if, for example, derived store is solely used as an argument for methods like sample, etc.

Maybe we could create an API for attaching logger to a particular derived store, which might look like this:

import { attachLogger } from 'effector-logger/attach';

const myComplextCombinedStore$ = combine(authState$, todos$, permissions$, combinator);
attachLogger(myComplextCombinedStore, 'myComplextCombinedStore$');

`effector-logger` breaks operations' priorities

Subj, effector-logger somehow breaks effector priorities, for example, sample began to work earlier, than .on, which completely breaks synchronous logic.

Code

const passingBy = createEvent();
const goAhead = createEvent();
const $gate = createStore(true)
  .on(passingBy, () => false)
  .on(goAhead, () => true);

sample({
  clock: passingBy,
  target: goAhead
});

passingBy()

works differently, when you import from from "effector-logger":

  • with import {} from "effector" store $gate contains true after calculations
  • with import {} from "effector-logger" store $gate contains false after calculations, because sample executes earlier, than .on(passingBy

Repo with reproduce: https://github.com/yumauri/effector-logger-issue

How to disable all Farfetched related logs

I'm using createJsonQuery and "effector-logger" in my project and I want to mute all farfetched related service logs from my console because they are too verbose and seem to clutter up the console. Please take a look on the screenshot.

Screenshot 2023-07-14 at 12 48 07

I've tried to use configure with { log: 'disabled' } for all states and effects from query returned by createJsonQuery(). But it didn't help. Could be someone can help to figure it out how to do that?

Screenshot 2023-07-14 at 12 47 33

Group logs to handle stacks

root.onCreateEvent(event => {
  const watch = event.watch
  event.watch = fn => watch(upd => {
    console.group(...)
    try {
      fn(upd)
    } finally {
      console.groupEnd(...)
    }
  })
})

Add babel-plugin

  • Remove module replacement recommendation from readme
  • Write babel plugin effector-logger/babel-plugin
  • Babel plugin should replace import {} from 'effector' to import {} from 'effector-logger'
  • ? Add support for root: replace import {} from 'effector-root' to import {} from 'effector-logger/root'
  • effector-logger/babel-plugin MUST be AFTER effector/babel-plugin

SyntaxError: Unexpected token u in JSON at position 0 when using chaining operator in store.map

Versions

  • effector: 22.2.0
  • effector-logger: 0.13.4
  • node: 14.19.1

Reproduction

Codesandbox (react + effector): https://codesandbox.io/s/serene-frog-rvcke7?file=/src/App.js

Steps to reproduce:

  1. Open sandbox repro
  2. Type some player name into input
  3. Click set player name
  4. Open console and you'll see this error: SyntaxError: Unexpected token u in JSON at position 0

What is expected?

Error is not expected because when I'm using createStore and createEvent from 'effector' - there is no error.

Important

I observe this error only when using the chaining operator ?. is store.map. For example, if we change this line: const $playerName = $player.map((player) => player?.name); to const $playerName = $player.map((player) => player ? player.name : null); - there is no error

Getting JSON parse error when calling events with no parameters after upgrade

What is the current behavior:
Hi, just upgraded to:

        "effector": "^22.1.1",
        "effector-logger": "^0.12.1",
        "effector-react": "^22.0.4",

Please provide the steps to reproduce and if possible a minimal demo of the problem via https://share.effector.dev, https://codesandbox.io or similar

export const resetSurvey = createEvent();

export default createStore<surveyStore>(emptySurveyStore)
    .on(resetSurvey, (state) => {
        return {
            ...state,
        };
    })

What is the expected behavior:
With the above snippet, nothing should change. However I'm getting a JSON parse error show in the console here:

$events
  .on(eventAdd, (map, payload) => ({
    ...map,
    [payload.name]: {
      mapped: payload.mapped,
      history: [],
    },
  }))
  .on(eventTriggered, (map, { name, params }) => {
    // should not change the order of fields

    map[name] = {
      ...map[name],
      history: [JSON.parse(JSON.stringify(params)), ...map[name].history],     <--- here
    };
    return { ...map };
  });

I'm guessing since the event has no params, it's trying to stringify/parse a null/undefined and that is causing the error.

Which versions of effector packages, and which browser and OS are affected by this issue? Did this work in previous versions of effector?:
yea used to work, I just reverted back to these and not seeing the error again

        "effector": "^21.8.5",
        "effector-logger": "^0.10.0",
        "effector-react": "^21.2.1",

CommonJS version tries to require() an ES Module and breaks

Maybe I'm missing something, but, to my understanding, the CommonJS version can't work because it forces a require() of an ES Module:

var effector_mjs = require('effector/effector.mjs');

Which of course leads to this error:

Error: require() of ES Module [EDITED]/node_modules/effector/effector.mjs not supported.
Instead change the require of [EDITED]/node_modules/effector/effector.mjs to a dynamic import() which is available in all CommonJS modules.

"Unexpected token u in JSON at position 0" when call event without payload

codesandbox

stacktrace ```

SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at eval (https://z2ihj.csb.app/node_modules/effector-inspector/index.mjs:1844:20)
at be (https://z2ihj.csb.app/node_modules/effector/effector.mjs:1067:71)
at et (https://z2ihj.csb.app/node_modules/effector/effector.mjs:1194:12)
at o (https://z2ihj.csb.app/node_modules/effector/effector.mjs:318:61)
at Function.create (https://z2ihj.csb.app/node_modules/effector/effector.mjs:386:19)
at r (https://z2ihj.csb.app/node_modules/effector/effector.mjs:380:22)
at onClick (https://z2ihj.csb.app/src/App.tsx:36:40)
at HTMLUnknownElement.callCallback (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:3945:14)
at Object.invokeGuardedCallbackDev (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:3994:16)
at invokeGuardedCallback (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:4056:31)
at invokeGuardedCallbackAndCatchFirstError (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:4070:25)
at executeDispatch (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:8243:3)
at processDispatchQueueItemsInOrder (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:8275:7)
at processDispatchQueue (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:8288:5)
at dispatchEventsForPlugins (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:8299:3)
at eval (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:8508:12)
at batchedEventUpdates$1 (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:22396:12)
at batchedEventUpdates (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:3745:12)
at dispatchEventForPluginEventSystem (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:8507:3)
at attemptToDispatchEvent (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:6005:3)
at dispatchEvent (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:5924:19)
at unstable_runWithPriority (https://z2ihj.csb.app/node_modules/scheduler/cjs/scheduler.development.js:468:12)
at runWithPriority$1 (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:11276:10)
at discreteUpdates$1 (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:22413:14)
at discreteUpdates (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:3756:12)
at dispatchDiscreteEvent (https://z2ihj.csb.app/node_modules/react-dom/cjs/react-dom.development.js:5889:3)
```

effector version: 22.1.2
effector-logger version: 0.13.0

Option to allow disabling console logs

Hi, I really like effector and everything around it. Would it be possible to add config option to be able to disable console logs, let say I am using redux tool and to have also console logs seems redundant? Thanks

Doesn't work with redux-devtools chrome extension

It gives an error

1.chunk.js:formatted:259960 TypeError: D.send is not a function
    at 1.chunk.js:formatted:140054
    at 1.chunk.js:formatted:140058
    at fe (1.chunk.js:formatted:142973)

D.send is reduxDevTools.send({
As I understand, this line https://github.com/effector/logger/blob/master/src/redux-devtools.ts#L8 should look like

typeof window !== "undefined" &&
window.__REDUX_DEVTOOLS_EXTENSION__.connect
  ? window.__REDUX_DEVTOOLS_EXTENSION__.connect()
  : window.__REDUX_DEVTOOLS_EXTENSION__;

If I try to debug, D is an object with just a connect function.

Can't setup logger

Please, clear out, what required steps to setup logger? Documentation says about:

  • babel-plugin (I do not use babel in project build). Therefore, I added plugin to storybook (wich uses babel) and nothing happens
  • replacing imports (I do not want to modify my sources for dev/prod builds, and do not know, how to setup replace imports automaticly in rollup),
  • calling attach to domain (I have no single root domain, and do not want to place debug call in every component, and remove it in production build). I can't use effector-root, because of p.2.

When I just simple call createInspector() I receive empty inspector window. Ho to add my stores to this inspector?

 "effector": "^21.7.5",
"effector-logger": "^0.9.0",
"effector-react": "^21.2.1",

effector/babel-plugin configuration doesn't work as expected

If reactSsr flag is provided through the effector-logger babel plugin - it does nothing

module.exports = {
  plugins: [['effector-logger/babel-plugin', { effector: { reactSsr: true } }]],
}

I've modified node-modules/effector/babel-plugin.js to see if rewrite actually happens

// node-modules/effector/babel-plugin.js#242
      ...
      if (reactSsr) {
        if (source === 'effector-react' || source === 'effector-react/compat') {
          path.node.source.value = 'effector-react/scope'
          console.log(source, 'rewrited')
        }
      }
      ...

It logs if effector/babel-plugin used directly, but not for effector-logger

Cyclic object value error

When I pass event or effect or what use(Unit/Store/Event and etc.) has returned me to handler of HTML5 element(like input or button) or UI component(MUI and etc.) and then start to interact with this element I catch an error with message Cyclic obejct value(Firefox) or called Converting circular structure to JSON(Chromium) or my tab falls. Also i tried to reproduce this script on my phone. Browser was falled.

Why i think that i bug in effector
Because, if i pass arrow-function into handler where i will be call event/effect and etc. and don't be pass event object, it will be work fine. But i can't do like this every time when i need because it's very uncomfortable

Please provide the steps to reproduce and if possible a minimal demo of the problem via https://share.effector.dev, https://codesandbox.io or similar
I couldn't to repeat it on others services

What is the expected behavior:
I expect It will be work like a simple handler

Which versions of effector packages, and which browser and OS are affected by this issue? Did this work in previous versions of effector?:
effector: 22.4.0
effector-react: 22.3.4
Firefox: 107
Chromium: 105
OS: Fedora 37
Kernel: 6.0.11

Logger shows some number instead of name

image

import { createDomain } from "effector";
import { attachLogger } from "effector-logger/attach";


export const countStore = createDomain()

attachLogger(countStore);

export const $count = countStore.createStore(0)

Error: combine expects a store in a field clock

Добрый день! когда мы подключаем logger к NextJs + effector в ts получаем ошибку "Error: combine expects a store in a field clock"

если из .babelrc убрать настройку logger то все работает и ошибки нет

codesandbox.io

Error: Error serializing `.initialState.bxdte["-2xkzew"].effect` returned from `getStaticProps` in "/catalog/[...slug]".

Когда используется effector-logger вместе с NextJs и effector22+, SSR\GSSP то,конфигурация babel заменяет импорты из 'effector' на "effector-logger" в следствии чего приложение падает из-за не соотвествия сериализации данных как я понял :\

"effector-logger": "^0.13.1",
"effector": "^22.1.1",
"effector-react": "^22.0.4",
"next": "^12.0.4",

Если убрать из конфигурации babel "plugins": ["effector-logger/babel-plugin"], то все работает, но нет логов :(

прошу рассмотреть доработку.

Any way to disable based on a flag/setting?

Hi, this is probably a dumb question, but if I build to production and don't change import { createEvent, createStore } from "effector-logger"; is there a way to turn it off using a flag or env var etc, or do I have to change the import?

Thanks!

Move effector-inspector to peer dependencies

In my project, I don't want to use effector-inspector, but it still installs and pulls a lot of unnecessary modules like solid.
I suggest to add effector-inspector to peer dependencies and install it by demand.

Debug domain with settings is not working

I need to disable logging to the console for all effector modules.
Since it has no opportunities to disable it globally I've followed Debug domain with settings to do it manually for every module.

For example, I've got the next code, but it's not working. I still get logging for the detail module.

import { createDomain } from 'effector'
import { attachLogger } from 'effector-logger/attach'

const domain = createDomain('detail')

export const fetchDetailFx = domain.createEffect()

export const setDetail = domain.createEvent()
export const clearDetail = domain.createEvent()

export const $detail = domain.createStore({})

attachLogger(domain, { console: 'disabled' })

What do I do wrong?

ReduxDevtools doesn't see effector-logger

ReduxDevtools doesn't see attached effector-logger printing No store found.

I'm using NextJs and attaching the logger like this:

if (!isServer) {
    const { attachLogger } = require('effector-logger/attach');

    attachLogger(rootDomain, { reduxDevtools: 'enabled', console: 'enabled' });
}

The console.log is working, though

logger throws errors on circular references

in here:

function copy<T>(a: T): T {
  return JSON.parse(JSON.stringify(a));
}

This breaks if objects are not serializable. I have a tree nodes, which reference their parents and logging those should work.

RFC: Allow to configure effector-logger via babel-plugin settings

Problem

Currently, if effector-logger is added via babel-plugin, like this:

{
  "env": {
    "development": {
      "plugins": ["effector-logger/babel-plugin"]
    }
  }
}

There is no option to configure it in any way.

For e.g. i would prefer to keep easy one-line installation via plugin, but to disable logs to console in favor of inspector or redux-devtools

Propolsal

Allow configure effector-logger via plugin options, like it works now in attachLogger options

{
   "env":{
      "development":{
         "plugins":[
            [
               "effector-logger/babel-plugin",
               {
                  "reduxDevtools":"disabled",
                  "inspector":"disabled",
                  "console":"disabled"
               }
            ]
         ]
      }
   }
}

Error: sample: expect clock to be a unit (store, event or effect) or array of units

This seems similar to #75 except that the error is reported from sample rather than guard -- and I'm not using effector-logger.

sample(clock, source, fn) works fine, but when calling sample({ clock, source, fn, target }) I get this error:

Screenshot 2024-02-03 at 4 03 13 PM

I'm using effector with vite (& svelte but that doesn't seem relevant, as the code is compiled in a .ts file not a .svelte file).

The only effector library I'm using is:

    "effector": "^23.1.0"

and bundling is via:

    "tslib": "^2.6.2",
    "typescript": "^5.2.2",
    "vite": "^5.0.8"

Any suggestions? Any other useful info I can provide? Thanks!

(My workaround for now is to use store.getState() in a reducer to achieve the result that I would have gotten with sample())

Do not show SyntheticEvent object

Hi.

Сan replace SyntheticEvent with a string symbol because logging an entire SyntheticEvent object causes lags in the browser.

Current behavior:
image

Expected:
☄️effector event * → editRate('SyntheticEvent ')

Can't resolve 'process/browser' in ...\node_modules\forest'

Try to start project and gott error:

"Module not found: Error: Can't resolve 'process/browser' in 'C:\Users\20074894\WebstormProjects\project\node_modules\forest'
Did you mean 'browser.js'?"

Also I tried add Webpack plugins:

new webpack.ProvidePlugin({
  process: "process/browser",
}),
new webpack.ProvidePlugin({
  Buffer: ["buffer", "Buffer"],
})

But have not luck((

Select data type for logging

It will be nice to be able to choose what to log in the console and, mainly, in redux dev tools.
Like select only stores and events to be logged, otherwise, there's a lot of pollution by effects stores pending and inFlight in dev tools.

[BUG] attachLogger and createInspector - Payloads too large and input handler took lot of time

When:

  1. git clone [email protected]:accesso-app/frontend.git
  2. attachLogger to root
  3. createInspector after client initialization
  4. Without createInspector there is no "Application state or actions payloads are too large" and input handlers reduce time consuming to 300ms

Current behavior:

  1. Application state or actions payloads are too large making Redux DevTools serialization slow and consuming a lot of memory. See https://git.io/fpcP5 on how to configure it.
  2. 'input' handler took more then 1000ms
  3. This synthetic event is reused for performance reasons

Expected behavior:

  1. 'input' handler took less than 10ms without errors

Environment:

  • node vesrion: v14.15.3

Screenshots:

Screenshot 2021-02-26 at 10 32 00

Incorrect document usage breaks SSR

Nodejs have no document and effector-inspector is breaking application in case of importing 'effector-logger/inspector' on server. This line is dangerous even if createInspector is not called at all.

`effector-logger/attach` is not exist, only `/dist/attach` works

import { attachLogger } from 'effector-logger/attach';
Could not find a declaration file for module 'effector-logger/attach'. '/node_modules/effector-logger/attach.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/effector-logger` if it exists or add a new declaration (.d.ts) file containing `declare module 'effector-logger/attach';`ts(7016)

Works as expected

import { attachLogger } from 'effector-logger/dist/attach';

node

14.16.1

typescript

4.4.3

effector

22.1.1

effector-logger

0.13.0

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.