Тёмный

10. Design Logging System | Chain of Responsibility Design Pattern | Amazon System Design interview 

Concept && Coding - by Shrayansh
Подписаться 110 тыс.
Просмотров 53 тыс.
50% 1

This Chain of responsibility Design pattern has been asked in Amazon and many other top product based companies.
This pattern is used for many real time application usage like ATM design, Vending Machine design and Logging System design
➡️ Code (GitLab) Link:
Shared in the Member Community Post (If you are Member of this channel, then pls check the Member community post, i have shared the Git link there)
➡️ Become a Member: / @conceptandcoding

Опубликовано:

 

17 июн 2022

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 117   
@zishanshaikh9375
@zishanshaikh9375 6 месяцев назад
there are folks in the comment section questioning if COR is the right pattern for logger or it can be done differently, here is my two cents on this, reason why chain of responsibility is the right pattern here: let's take example of log4j, we can enable certain log level in the system like ERROR or INFO etc, this is how the error levels are defined ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF e.g. if log level is set to warn, then only warn, error, fatal will be printed, rest all logs with other log levels will be disabled like debug, info etc will not be printed Now you can see that chain of responsibility comes in handy here, lets say I have used warn as log level in log 4j and in code i have different logs like debug, info, error etc lets take error, it will go to all handlers and check what log level is enabled e.g. it will first go to debug handler, is it enabled, no, then go to next info and next warn, okay warn is enabled but the log level to be printed is error, then it will move to next handler i.e. error okay now it matches the log level to be printed and also at the system level warn is enabled and error handler is eligible for printing this log There is a order of execution here where the request may or may not be fulfilled based on what log level is enabled and the order which the request should be served is defined by the chain of responsibility pattern i.e. ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF
@rishabhshekharphukan5687
@rishabhshekharphukan5687 10 месяцев назад
This is where we actually implement a Linked List from scratch to solve a real world problem!! And this proves why understanding datastructures from scratch is important and not simply use library classes. Great video!! 💯
@user-og7de8ih4f
@user-og7de8ih4f Год назад
Spring Security Filter chain is the perfect example of this Design pattern in my opinion..where your authentication request goes through multiple Authentication Provider
@akshatsingh02
@akshatsingh02 7 месяцев назад
Yeah, correct and not only Security Filter chain, it can be any Filters in Servlets or Interceptors in Struts2.
@user-gz6ml8ts3f
@user-gz6ml8ts3f 7 месяцев назад
As a matter of fact, a set of middlewares that process a request in the request reply pattern happen to follow COR patter
@arunshrivastava7513
@arunshrivastava7513 7 месяцев назад
How to decide when to use if-else / switch-case and when to use chain of responsibility pattern? Like in case of logger since we already know about all the handlers and the chain order in advance why not use if-else statement for each log level
@jayantjain1519
@jayantjain1519 Год назад
Man , you're the best person for this content❤❤❤ . Definitely recommending this channel to many.
@ConceptandCoding
@ConceptandCoding Год назад
Thank you
@Rakeshkumar-po2yg
@Rakeshkumar-po2yg Год назад
apki understanding bahot acchi hai. mujhe kafi benifit mila
@ConceptandCoding
@ConceptandCoding Год назад
Glad to know that
@abhishekpattnaik8531
@abhishekpattnaik8531 Год назад
Great Quality content with simple explanation. Thanks
@ConceptandCoding
@ConceptandCoding Год назад
Thanks 👍
@kashifjamil4403
@kashifjamil4403 8 дней назад
first of all, doing great work. I have a suggestion that it should not be the responsibility of main method to invoke the info or debug logger rather the logProcessor should be responsible of creating the chain of log processors and main method just invoke the logger and then calls it for printing logs
@ConceptandCoding
@ConceptandCoding 8 дней назад
Yes, that's a good suggestion buddy. The main method should simply invoke the logger, which then processes the logs through the chain. This keeps the main method clean and focused on its primary responsibilities.
@goelshubham46
@goelshubham46 7 месяцев назад
idk but does this design pattern really helps? The problem it is trying to solve can be easily solved by data structure or even by if else conditions if levels are not too many. why i would want the flow to reach it to error via info or log when i can reach there directly? or in vending machine if i want water why do i want the flow go via pepsi or coke??
@manishbansal3861
@manishbansal3861 2 месяца назад
great example. Just one question, why can't we use switch case here to get exact match of that object type and call its method? if none is found, default case would return.
@vnitish14
@vnitish14 Год назад
highly underrated playlist for System design interview prep.
@ConceptandCoding
@ConceptandCoding Год назад
Thanks
@codinggist7761
@codinggist7761 Год назад
First of all great content. I love watching your playlist. 1 question, why not enums & static vars?
@theaverageladka2265
@theaverageladka2265 Месяц назад
Hey @shreyansh , can we also use factory pattern for logging as in the video itself the logging level can be determined using the type like info, debug or error and based on the type the implementing class can print the statement ? Just curious about the different approach in this logging specific problem. Although I understood the case where the rs 2000 were being fetched from ATM.
@sumitbasu5146
@sumitbasu5146 Год назад
Very helpful video..Thank you for sharing your knowledge 👏👍
@ConceptandCoding
@ConceptandCoding Год назад
Thanks
@vishalbhardwaj8577
@vishalbhardwaj8577 Год назад
Hey just a question, why can't we have three different objects and use something like a factory pattern to dynamically select the object on basis of some string(info, debug or error) and then invoke that object's logging function. Why do we need to maintain a chain of responsibility
@dhvanilparikh6128
@dhvanilparikh6128 Год назад
I was thinking this too. This pattern might be more relevant for ATM where we want to dispatch the biggest note first and then the smaller ones.... for logger I think Factory should be fine?
@akshitbansal5651
@akshitbansal5651 Год назад
@@dhvanilparikh6128 even in ATM, the simple coin DSA question would be able to solve it.
@2006kenblock
@2006kenblock 11 месяцев назад
I feelfactory pattern should be a better candidate as well for a logger.
@varunr3055
@varunr3055 5 месяцев назад
ATM is an excellent example where this pattern can be used. consider a user sends a request to withdraw 5000 with his card, the system can have different handler like Card Number checker, ATM card expiry checker, user's entered pinchecker and User's balance Checker. So all these checkers have a chain of responsibility. In case the user enters a card that is not even an ATM card then the request ends there, else the responsibility goes to next Card expiry and then pinchecker and then balance checker. In strategy or abstract factory,there is no chaining. We use one strategy or the other. Forgive the bad formatting I'm typing this on my tablet using handwriting recognition
@maggs2960
@maggs2960 5 месяцев назад
Why do we use abstract class instead of normal class in Responsibility chain design pattern, when we don't have any abstract methods inside it?
@pulakammalathy6968
@pulakammalathy6968 3 месяца назад
great video. one doubt is , cant we use simple factory pattern also to solve logger question ? based on log type in request, factory will return corresponding logger class and we will call log method in that class
@SugamMaheshwari
@SugamMaheshwari 2 месяца назад
Yeah mee too was thinking on the similar lines, that factory pattern would also be a great use-case for logger example. I think shrayansh was more focused on explaining the chain of responsibility design pattern and therefore the example. In one of my past companies a good use case of this pattern is in trading simulator setup (Obviously, Connecting the dots backwards :) 1. read_market_data -> 2. build_order_book -> 3. send_data_to_strategy.... Here the sequence of events form and share the chain of responsibility.
@HimanshuKumar-xz5tk
@HimanshuKumar-xz5tk 8 месяцев назад
how to decide whether to use factory or chain of responsbility principle in use cases like logger?
@aashishgoyal1436
@aashishgoyal1436 Год назад
Brilliant content as always Keep it up Shrayansh
@ConceptandCoding
@ConceptandCoding Год назад
thank you
@vyankateshkulkarni4374
@vyankateshkulkarni4374 Месяц назад
great explanation... thanks sir ji... though the video length is 15min only.. one might need to spend more time understanding how this chain is transferring their responsibilities to next chained object.
@BRIJKISHOREDUTTBCE
@BRIJKISHOREDUTTBCE 3 месяца назад
Hi Shrayansh, can you give the insights about logging mechanism in distributed micro-services in HLD video?
@rishiagrawal_mtr
@rishiagrawal_mtr 3 месяца назад
Awesome explanation. can you help me understand why we prefer this design pattern over just simple if/else in the base class to create different logger object? to avoid unnecessary iteration over complete list
@ConceptandCoding
@ConceptandCoding 3 месяца назад
usage of design pattern is not mandatory at all, all your classes and relationships should fulfill SOLID principles, So you can also do that with if-else till its not breaking solid principles.
@geekydanish5990
@geekydanish5990 2 года назад
Awsome content keeping posting
@ConceptandCoding
@ConceptandCoding 2 года назад
thanks
@siddharth1700
@siddharth1700 7 месяцев назад
Given the number of log levels are fixed. A EnumMap with Map would have been faster and maintainable compared to chain of responsibility design pattern.
@ujjwalgupta1318
@ujjwalgupta1318 3 месяца назад
For the logger method, we could have simply used Factory design pattern to determine the correct logger as per the enum passed, why do we need a chain of responsibility pattern? In this scenario, why should an error message be even processed by InfoLogProcessor?
@sunnykumarsingh7039
@sunnykumarsingh7039 3 месяца назад
Exactly
@drrrpp
@drrrpp 27 дней назад
can this can be used for employee detail check scenario, say aadhar,pan,bank details checking one after one ??
@anunaykumar2871
@anunaykumar2871 Год назад
in the main class we have made an nested initialization to the Logger class.But in actual production code there is no such nested initialization in Log4j sdk .How does that works internally then?
@shubhshah4192
@shubhshah4192 10 месяцев назад
Most probably there is a wrapper class which returns the chained object
@avinashak3302
@avinashak3302 2 года назад
Thank you Awesome explanation :)) waiting for next one!
@avinashak3302
@avinashak3302 2 года назад
can you add Git link please ? if possible
@ConceptandCoding
@ConceptandCoding 2 года назад
Hi Avinash, pls find the git link gitlab.com/shrayansh8/interviewcodingpractise/-/tree/main/src
@ConceptandCoding
@ConceptandCoding 2 года назад
Also one gentle request, if you find video helpful pls do share it with your connections . thanks
@avinashak3302
@avinashak3302 2 года назад
@@ConceptandCoding Yep i have suggested your channel in my team they are finding to really helpful
@avinashak3302
@avinashak3302 2 года назад
Please keep posting in long run your efforts will pay off. You are making many early stage devs like me life easier
@adityaagrawal3201
@adityaagrawal3201 Год назад
can logger be implemented with observer pattern as well..? Where an error been written to multiple type of file or console..?
@ConceptandCoding
@ConceptandCoding Год назад
umm, you mean to say, console, file loggers will act as observer?
@indianathena219
@indianathena219 2 месяца назад
I was recently asked in an interview to design multi tier LRU cache where each layer will have increasing size and time of retrieval. Can this be done using chain of responsibility considering if element is found, we need to populate it backwards in all previous layers for cache to be updated?
@ConceptandCoding
@ConceptandCoding 2 месяца назад
Yes, you can design a multi-tier LRU cache using the Chain of Responsibility pattern, ensuring that when an element is found in a higher tier, it gets populated backward in all previous layers for cache update.
@akhilaluwala8766
@akhilaluwala8766 Год назад
. This logger can be implemented by strategy design pattern or abstract design pattern also ri8 since based on loglevel type we are implementing respective class.. whats is the use of chain of processing in classes as we know which log level type need to be used..
@HEMANTVERMA-pv2pe
@HEMANTVERMA-pv2pe Год назад
I also came up with that at first. It would be nice to see the arguments to use both. @ConceptandCoding
@varunr3055
@varunr3055 5 месяцев назад
ATM is an excellent example where this pattern can be used. consider a user sends a request to withdraw 5000 with his card, the system can have different handler like Card Number checker, ATM card expiry checker, user's entered pinchecker and User's balance Checker. So all these checkers have a chain of responsibility. In case the user enters a card that is not even an ATM card then the request ends there, else the responsibility goes to next Card expiry and then pinchecker and then balance checker. In strategy or abstract factory,there is no chaining. We use one strategy or the other. Forgive the bad formatting I'm typing this on my tablet using handwriting recognition
@premium3968
@premium3968 Год назад
This 1 was best
@ConceptandCoding
@ConceptandCoding Год назад
Thanks
@devanshhalwai9655
@devanshhalwai9655 10 месяцев назад
Hey! for this logger implementation can we not use factory design pattern where it can provide me the instance of logger based on the requirement ?
@ConceptandCoding
@ConceptandCoding 10 месяцев назад
Factory design pattern is creational design pattern, which mostly focus on creating of object. So don't this we should use it here
@LegitGamer2345
@LegitGamer2345 10 месяцев назад
@@ConceptandCoding Could you elaborate a bit on when we to use factory pattern and when to use chain of responsibility pattern? It seems like even in chain of responsibility pattern we are creating multiple objects ?
@harishaseri
@harishaseri Год назад
Hey . Like you said that vending machine can be designed by the state design pattern(in vending machine design video) and here you are saying that we can do this with chain of responsibility as well. I think ATM can also be designed by State design pattern . what do you think about it ?
@ConceptandCoding
@ConceptandCoding Год назад
yes, pls check my ATM video
@harishaseri
@harishaseri Год назад
@@ConceptandCoding got it . thanks
@abhijeetbasfore6816
@abhijeetbasfore6816 Год назад
Great
@ConceptandCoding
@ConceptandCoding Год назад
Thanks
@nagaakhilbelide3569
@nagaakhilbelide3569 2 дня назад
Can't we use a Factory pattern for logging? So, based on the LogLevel, we can return the corresponding object.
@ConceptandCoding
@ConceptandCoding 2 дня назад
yes we can
@gauravbansal1894
@gauravbansal1894 Год назад
Thanks for the video. One doubt why can't we use the factory pattern here?
@ConceptandCoding
@ConceptandCoding Год назад
Factory pattern is a creational type. It's job is to create objects. But here we are not creating objects. So the nature of work or you can say intention is different Gaurav
@gauravbansal1894
@gauravbansal1894 Год назад
@@ConceptandCoding understood thanks and your videos are amazing
@volamjeevankumar1502
@volamjeevankumar1502 Год назад
Whats the benefit of writing log processor class as abstract
@ConceptandCoding
@ConceptandCoding Год назад
I want to create child classes, you can try creating Interface too.
@nitishprasadkushwaha
@nitishprasadkushwaha 11 месяцев назад
awsomne
@ConceptandCoding
@ConceptandCoding 11 месяцев назад
Thanks
@art4eigen93
@art4eigen93 Год назад
isn't State DP used to design Vending machines?
@ConceptandCoding
@ConceptandCoding Год назад
Right but there is no one solution Aritra.
@hrithikbabbar5721
@hrithikbabbar5721 11 месяцев назад
Loggers also come in singleton???
@ConceptandCoding
@ConceptandCoding 11 месяцев назад
Yes
@sushilverma6192
@sushilverma6192 Год назад
For a logger implementation, what is the actual difference between COR pattern and decorator pattern?
@rajdeepchauhan5251
@rajdeepchauhan5251 Год назад
According to my understanding, in CoR every object has its own implementation and handling logic but in case of decorator pattern, we work on the same object and define different decorators to decorate the object. We can not break the flow in case of decorators as well. [ Taken from refactoringguru ] Chain of Responsibility and Decorator have very similar class structures. Both patterns rely on recursive composition to pass the execution through a series of objects. However, there are several crucial differences. The CoR handlers can execute arbitrary operations independently of each other. They can also stop passing the request further at any point. On the other hand, various Decorators can extend the object’s behavior while keeping it consistent with the base interface. In addition, decorators aren’t allowed to break the flow of the request.
@nitigya
@nitigya Год назад
Why are we not using the factory design pattern?
@mohdnomaankhan2435
@mohdnomaankhan2435 Год назад
+1
@ashishgulati9539
@ashishgulati9539 Год назад
+1
@sombuddhachakravarty4142
@sombuddhachakravarty4142 Год назад
For this kind of design, why can't we use Factory pattern? Factory can return the required kind of class based on log level, and then use that to print the log in proper format.
@ConceptandCoding
@ConceptandCoding Год назад
This kind of design is used when you don't know which class can fulfill the request, so it goes in chain and which ever say yes i can fulfill, it will handle the request, in that case factory pattern will not fit
@sombuddhachakravarty4142
@sombuddhachakravarty4142 Год назад
@@ConceptandCoding For ATM I agree that the COR pattern makes sense. For the logger use case we can only have a fixed number of levels that are there as an ENUM. So we can switch over the passed ENUM value to get the correct object. We can use a singleton factory to not generate new objects everytime
@akshitbansal5651
@akshitbansal5651 Год назад
why can't we have different methods like logE, logI, logW?
@trident8638
@trident8638 Год назад
Ideally one class should have only one responsibility as per SOLID principle. Think of error reporting class, currently it is logging an error on console but in future we might wanna send some alarms to dev teams related to error count, we can build dashboard for service health. If we have all logging method in one class then in future that class will be too cluttered
@nitishprasadkushwaha
@nitishprasadkushwaha 11 месяцев назад
binge watching to save myself from getting new membership next month . xD , but coding is taking time .
@ConceptandCoding
@ConceptandCoding 11 месяцев назад
:) happy learning buddy but do practice with hands.
@nitishprasadkushwaha
@nitishprasadkushwaha 11 месяцев назад
@@ConceptandCoding Thanks for keeping it at such low cost , means a lot for guys like me.
@ConceptandCoding
@ConceptandCoding 11 месяцев назад
@@nitishprasadkushwaha :) even though it's low but it will make you think twice before you even think to purchase course for 5k or 10k rs.
@pawnyogi
@pawnyogi 9 месяцев назад
How to access car rental and car parking lot video ?
@ConceptandCoding
@ConceptandCoding 8 месяцев назад
Those are accessed to members buddy. You will see join button at home page, there you can select "Unlock LLD" option.
@vishnuvadhandevandla4110
@vishnuvadhandevandla4110 11 месяцев назад
pls do english version
@ConceptandCoding
@ConceptandCoding 11 месяцев назад
All latest videos are in English only, few were in hindi. Will try to cover it in English, in Live LLD playlist (as I have covered few hindi topics in English in that playlist)
@shasha6538
@shasha6538 Год назад
iska gitlab link nhi hai kya?
@ConceptandCoding
@ConceptandCoding Год назад
Check here pls gitlab.com/shrayansh8/interviewcodingpractise/-/tree/main/src/LowLevelDesign
@weborntolead5332
@weborntolead5332 Год назад
Where is the repo link? Pz send me here.
@ConceptandCoding
@ConceptandCoding Год назад
gitlab.com/shrayansh8/interviewcodingpractise/-/tree/main/src/LowLevelDesign
@okeyD90232
@okeyD90232 Год назад
This could be simplified by using abstract method template with above implementation, so that you only care about how to log not when to log. The code would look like Your abstract Processor class would look like this: constructor(nextLogger) { .... } protected Logger nextLogger = null; public final void log(int logLevel, String message){.
@ConceptandCoding
@ConceptandCoding Год назад
Thanks
@homestaysandcafes
@homestaysandcafes Год назад
Sir code not working for me it is going in infinite loop😢
@ConceptandCoding
@ConceptandCoding Год назад
strange it worked for me, Can you pls debug whats the issue.
@homestaysandcafes
@homestaysandcafes Год назад
Debugged my issue sir, actually instead of if condition i was using while thats why it was going in infinite loop 😂😂😂
@ConceptandCoding
@ConceptandCoding Год назад
:) good 👍
@tansenmusician9494
@tansenmusician9494 Месяц назад
Isn't this design bad. Suppose in future we create a new handler and they fail to implement next logic properly then the whole system goes for a toss.
@sushil1922
@sushil1922 Год назад
Kindly allow access to all videos @ConceptAndCoding
@yatri6329
@yatri6329 2 месяца назад
But ATM/Vending machine to State design ka use krte h na??
@ConceptandCoding
@ConceptandCoding 2 месяца назад
same question can be solved using different design patterns and different ways. So there is no 1 solution
@manishsakariya4595
@manishsakariya4595 4 месяца назад
May be more simple implementation package LLDQuestions.Logger.LoggerBasic; import java.io.IOException; import java.io.PrintWriter; enum LogLevel { INFO, WARNING, ERROR } interface LogSink { void log(String message); } class ConsoleSink implements LogSink { @Override public void log(String message) { System.out.println(message); } } class FileSink implements LogSink { private String filename; public FileSink(String filename) { this.filename = filename; } @Override public void log(String message) { try (PrintWriter writer = new PrintWriter(filename)) { writer.println(message); } catch (IOException e) { e.printStackTrace(); } } } class Logger { private LogLevel logLevel; private LogSink logSink; public Logger(LogLevel logLevel, LogSink logSink) { this.logLevel = logLevel; this.logSink = logSink; } public void log(LogLevel level, String message) { if (level.ordinal() >= logLevel.ordinal()) { String logMessage = "[" + level + "] " + message; logSink.log(logMessage); } } } public class Solution { public static void main(String[] args) { LogSink consoleSink = new ConsoleSink(); LogSink fileSink = new FileSink("log.txt"); Logger consoleLogger = new Logger(LogLevel.INFO, consoleSink); Logger fileLogger = new Logger(LogLevel.WARNING, fileSink); consoleLogger.log(LogLevel.INFO, "This is an info message"); consoleLogger.log(LogLevel.WARNING, "This is a warning message"); fileLogger.log(LogLevel.ERROR, "This is an error message"); } }
Далее
3M❤️ #thankyou #shorts
00:14
Просмотров 8 млн
The tactic worked 😂#shorts by  Leisi Show
00:26
Просмотров 3,8 млн
5 Design Patterns That Are ACTUALLY Used By Developers
9:27
Amazon System Design Interview: Design Parking Garage
29:59
System Design: Design a URL Shortener like TinyURL
16:00
How I Mastered Low Level Design Interviews
8:41
Просмотров 46 тыс.
3M❤️ #thankyou #shorts
00:14
Просмотров 8 млн