pollyjs icon indicating copy to clipboard operation
pollyjs copied to clipboard

feature: provider alternate logger

Open alexlafroscia opened this issue 6 years ago • 5 comments

Description

I'd like to be able to override the method use to log to the console. Rather than assuming we always want to call console.log, it would be cool if that is a default but overridable with a user-provided function with some given signature.

One use-case is logging the mocked requests into the Cypress command log, so that it's clear what is going on in Polly during your tests. https://docs.cypress.io/api/commands/log.html

If you are interested in a feature like this, I'm happy to open a pull request for it.

Proposed Syntax

I would propose that, in addition to configuring logging being enabled or disabled, an alternate logger can be provided. That could look something like this:

new Polly("..", {
  logging: true,
  logger: {
    log() { ... }
  }
})

it might be interesting to allow logger itself to be a function that returns an object with the desired properties, like so:

new Polly("..", {
  logging: true,
  logger: () => ({
    log() { ... }
  })
})

alexlafroscia avatar Apr 09 '19 01:04 alexlafroscia

Seems reasonable, I'd happily review/accept a PR for this.

jasonmit avatar May 31 '19 01:05 jasonmit

A simple fix would be exposing Logger.

import Logger from '@pollyjs/core/src/-private/logger.js'
const myLogger = new Logger(Polly)

This doesn't work at the moment unless you transpile logger.js.


Workaround

This is an example of removing the request logging and just showing whether something is replayed or reecording.

import { ACTIONS } from '@pollyjs/utils'

function patchLogger(logger) {

 const FORMATTED_ACTIONS = {
   [ACTIONS.RECORD]: 'Recorded',
   [ACTIONS.REPLAY]: 'Replayed',
   [ACTIONS.INTERCEPT]: 'Intercepted',
   [ACTIONS.PASSTHROUGH]: 'Passthrough'
 };

  logger.logRequest = (request) => {
   if (request.config.logging) {
     logger.groupStart(request.recordingName);

     console.groupCollapsed(
       `${FORMATTED_ACTIONS[request.action]} ➞ ${request.method} ${
         request.url
       } ${request.response.statusCode} • ${request.responseTime}ms`
     );
     //console.log('Request:', request);
     //console.log('Response:', request.response);
     //console.log('Identifiers:', request.identifiers);
     console.groupEnd();
   }
 }
}

vjpr avatar May 17 '21 13:05 vjpr

@vjpr are you needing this because the logger is too noisy? Would having something like logging: true | false | 'compact' | 'verbose' solve this for you?

offirgolan avatar Jun 02 '21 17:06 offirgolan

Another workaround is to set logging: false and add your own custom logging middleware.

polly.server.any().on('response', (req) => { /* custom logging logic */})

offirgolan avatar Jun 02 '21 17:06 offirgolan

I want to be able to see only when something is being replayed/recorded - not the full logs.

vjpr avatar Jun 02 '21 20:06 vjpr