# Logging observable values while extending service

I'm trying to extend a service function which returns an Observable<T>. The idea is to extend the function so I can add logging functionality whenever the observable emits a new value.

fromEvent<T>(eventName: string): Observable<T> {
super.fromEvent(eventName).subscribe(
function next(data) {
console.group();
console.log('----- SOCKET INBOUND -----');
console.log('Action: ', eventName);
console.log('Payload: ', data);
console.groupEnd();
}
);

return super.fromEvent(eventName);


How can I make my function more effective? Because whenever fromEvent() is invoked a subscription is created and an observable is returned from the base class. As I understand, all subscriptions should at some point be unsubscribed.

Or are there any other way you could implement a logging functionality on an observable that listens to a specific event?

## 1 Answer

One way to achieve what you want is to use .do() and may be .catch() operators.

.do() operator taps on a target stream and executes a function on each non-error event in the stream. It is designed specifically for this purpose, which you can define more generically as side effects:

This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. -- RxJs docs

Notice that .do():

1. does NOT affect the original Observable stream in any way. This function itself returns an Observable of the same type as the original one.
2. does NOT subscribe to the original Observable, so the .subscribe() invocation is required down the road.
3. does NOT react to error events in the original Observable. Therefore, you may want to use .catch() to log the errors.

fromEvent<T>(eventName: string): Observable<T> {
return super
.fromEvent(eventName)
.do(eventData => {
console.group();
console.log('----- SOCKET INBOUND -----');
console.log('Action: ', eventName);
console.log('Payload: ', eventData);
console.groupEnd();
})
.catch(error => {
console.group();
console.error('----- SOCKET INBOUND -----');
console.error('Action: ', eventName);
console.error('Error: ', error);
console.groupEnd();
});
}

• I use '.do()' almost daily with ngrx/effects, can't believe I couldn't connect the dots :). Thanks tremendously for your help! – Andreas Johansson Jan 1 '18 at 2:14
• @AndreasJohansson yeah, no problem. This happens to all of us time to time. – Igor Soloydenko Jan 1 '18 at 3:07