<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hardik Taluja on Medium]]></title>
        <description><![CDATA[Stories by Hardik Taluja on Medium]]></description>
        <link>https://medium.com/@hardiktaluja?source=rss-8fb52a033356------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-M_yNYGWDkdU7BPDV9blA.jpeg</url>
            <title>Stories by Hardik Taluja on Medium</title>
            <link>https://medium.com/@hardiktaluja?source=rss-8fb52a033356------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:41:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hardiktaluja/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Migrating to Google Cloud Spanner]]></title>
            <link>https://engg.glance.com/migrating-to-google-cloud-spanner-2a315427796f?source=rss-8fb52a033356------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a315427796f</guid>
            <category><![CDATA[distributed-sql]]></category>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[cloud-spanner]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Hardik Taluja]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 06:06:33 GMT</pubDate>
            <atom:updated>2022-12-21T08:10:16.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g6E5QNtbxLM2GnK3" /><figcaption>Photo by <a href="https://unsplash.com/@mattartz?utm_source=medium&amp;utm_medium=referral">Matt Artz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This blog covers a typical migration journey from your existing database to Google Cloud Spanner DB.</p><p>I will try to cover the entire journey into three parts — essential things to do before, during, and after migration, so that you can also follow along similar lines and ensure a smooth migration of your data.</p><p>So, let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7G4bEsuCCv-px8oVIRu9w.png" /></figure><p>First things first, there are a lot of things that you need to explore before getting started with the migration process.</p><h3>What is Google Cloud Spanner?</h3><p>Google Cloud Spanner is a fully managed <strong>Distributed Relational</strong> Database with unlimited scale, strong consistency, and up to 99.999% availability.</p><p>The main catch is that it is a relational database that can scale horizontally. This was the major problem with traditional relational databases, due to which we had to move to NoSql Databases.</p><h3>Understand your requirements</h3><p>Let’s consider two scenarios here:</p><ol><li>You are already on an existing traditional SQL database with a lot of databases, tables, and relationships between them. And you have a huge volume of concurrent transactions throughout the day but are struggling with scaling issues.<br>OR</li><li>You are currently on a NoSql database, the scale is getting handled pretty well. But you are compromising with either availability, eventual consistency, or having some workarounds for fulfilling the transactional use cases. And now you feel that these workarounds are becoming an overhead and take a lot to maintain.</li></ol><p>If any of these seems to be applicable to you, then distributed SQL databases should be on top of your list.</p><h3>Don’t take my word, do POCs for your use cases</h3><p>We also did a lot of POCs and benchmarking against different databases to come to the conclusion of choosing the database that fit our requirements.</p><p>This would typically include:</p><ul><li>Understanding what existing workflows are and why you want to migrate those.</li><li>Is there an existing schema? Yes, or No, what should be the schema now? This is a very good time to fix all the mistakes that were done in the existing design.</li><li>Finalized your schema? Now go through the various distributed SQL database options that are there in the market.</li><li>Run tests on prod-like data and traffic on the databases that you shortlisted.</li><li>Run a lot of short-span load tests with varying instance and test configurations.</li><li>I repeat — run a lot of tests.</li><li>Run an endurance test for at least more than a day — actual prod performance can be measured very clearly with this.</li><li>Check whether the DB was able to handle the load for longer durations.</li><li>Check for performance during traffic spikes.</li><li>Are the latencies under control during peak loads?</li><li>Achieve the correct instance sizing during the tests — this will help in evaluating costs for running your database, and comparing it with the other options.</li><li>Check out what autoscaling methods the database provides.</li></ul><p>Let’s assume that Google Cloud Spanner emerges as the final choice after all the above experiments, features, and cost comparisons.</p><p>So now, let’s dive deep into more details on Spanner.</p><h3>Some features of Spanner</h3><ul><li>ACID transactions</li><li>Strong transactional consistency</li><li>Horizontally Scalable: Just add more nodes as and when required</li><li>99.999% availability guarantee from Google</li><li>Online Schema Updates: No downtime for schema updates, such as adding secondary indexes, additional columns</li><li>TTL: Can be set up on a table level which runs as a low-priority background process</li><li>Observability: Metrics with Cloud Monitoring, Key Visualizer for Data Storage and Query Distribution Trends, Query Insights for visualizing query performance metrics and debugging issues</li></ul><p>For the entire list of features, check out the official Spanner docs.</p><p><a href="https://cloud.google.com/spanner#section-8">Cloud Spanner | Google Cloud</a></p><h3>How does Cloud Spanner work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QIsiKtASqiim0mdAaXvTw.png" /></figure><p>Not going into details, the image should be self-explanatory. If not, do check out the source blog for this.</p><p><a href="https://cloud.google.com/blog/topics/developers-practitioners/what-cloud-spanner">What is Cloud Spanner? A gcpsketchnote cheat sheet | Google Cloud Blog</a></p><p>Now that you have selected Spanner as your DB choice and also you know a bit about Cloud Spanner’s working, let’s now focus on the migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeCSADahs1WKuSeTRCeuWA.png" /></figure><p>There are a ton of activities that need to be performed during this phase. Let’s check these one at a time.</p><h3>Design DBs and Tables</h3><p>Whatever the existing design was, now is the time to either use it as it is or to do some brainstorming about the final schema for Spanner.</p><p>Here are some of the things that you might consider discussing.</p><ul><li>How the DBs and tables would look like?</li><li>What would be the relationship between the tables?</li><li>What primary key to use for the tables?</li><li>What would be the query access patterns?</li><li>What indexes would be required?</li><li>Do we need TTL?</li><li>Do we often need data from multiple tables?</li><li>What does the schema evolution look like?</li></ul><p>And so on…</p><h4>Remodeling and course correction opportunities</h4><p>As mentioned earlier also, migration is a great time to remodel the database as per the evolving use cases, as you would be having a fresh start with the new database, and can correct whatever mistakes or workarounds were put into place in the existing world.</p><h4>Cleanup</h4><p>Most of the time, the entire data does not need to be migrated to the new database.<br>There would be some tables/collections, columns, or indexes that were added for some use cases, and are now deprecated, but were not cleaned up in the existing schema (maybe because of some dependencies, or just because of the NoSql design, data just lying in the existing documents) — these can be avoided in the migration itself.</p><h4>Follow best practices and avoid anti-patterns for Spanner</h4><ul><li>Be cautious of the choice of the primary key for your tables — Choose a primary key that avoids hotspots.<br>For eg — Choosing an auto-incrementing primary key would result in the new row always going to the split with the last key range.<br>UUID is a good choice for ensuring the new row insertion is spread across random range splits each time.</li><li>To use foreign keys or Interleaved tables — Foreign key concept is similar to what we have in traditional SQL databases. Interleaved table is a new concept in which you store the child table rows along with the parent table’s row so that Spanner tries to store all those rows in the same split for faster access.</li><li>Secondary indexes — Create secondary indexes for columns that are frequently used in your queries to fetch data.</li><li>Composite secondary indexes — if you have created a secondary index using more than one column, then make sure that the queries specify those columns in the same order as they were used while creating the index. Also, if using only fewer columns in the query than the index, make sure that the order of the columns is a prefix of the index definition columns order.</li><li>Stored columns — If some columns are very frequently accessed in the queries which use an index, then that column can be used as a stored column with the index definition itself so that it does not have to refer to the original record for getting that column.</li></ul><p>There are a lot more things to take care of as part of following the best practices while designing your schema.</p><p>Do check out the Spanner docs for more details:</p><p><a href="https://cloud.google.com/spanner/docs/schema-design">Schema design best practices | Cloud Spanner | Google Cloud</a></p><h3>Application side changes</h3><p>Assuming there will be a few schema changes, there definitely will be application-level changes in the Data Access Layer.</p><p>Whatever language your application is written in, Spanner provides multiple client libraries for almost all the major languages. Do check out the client libraries as per your applications.</p><p><a href="https://cloud.google.com/spanner/docs/reference/libraries">Spanner client libraries | Google Cloud</a></p><p>Before moving to the migration strategies, a word of advice:</p><p><strong>Whatever migration strategy you choose, always have a flag in your application that allows you to switch the data source without changing any code. This will be helpful to avoid separate versions of your code, plus in case of rollbacks as well.</strong></p><h3>Migration Strategy</h3><p>Once done with the schema design and application side changes, you need to choose the migration strategy that you want to follow.</p><p>Again there are two ways you can proceed from here:</p><h4>Offline Migration</h4><p>This strategy involves downtime and mostly consists of these steps:</p><ol><li>Take a planned downtime.</li><li>Stop all traffic on your existing database.</li><li>Take a snapshot of the existing database.</li><li>Run a bulk import job as per your requirements and schema, to import data to Spanner.</li><li>Do a quick validation for records by running a small script for comparing a few records across both data sources.</li><li>Warm up the Spanner instance with prod-like traffic before enabling the actual traffic.</li><li>If everything looks good, start enabling traffic to Spanner from the application in a stepwise manner.</li><li>Also, make sure that you are still capturing the writes from Spanner, and propagating them to the existing database, so as to roll back to the original source, just in case something goes wrong.</li></ol><h4>Online Migration</h4><p>If the above process is not feasible for your business, or the duration for above is expected to go over the allowed downtime, then you need to follow live migration of your database, with minimal downtime during the switchover.</p><p>This is a lot more complex, and you need to take care of the following things:</p><ol><li>As we would not be stopping the traffic on the existing database, then we would have to do this in two steps — bulk import, and then migration of delta records that came up while bulk import was running.</li><li>Start capturing the writes from the existing data source — CDC queue.</li><li>Take a snapshot of the existing database.</li><li>Run a bulk import job as per your requirements and schema, to import data to Spanner.</li><li>Do a quick validation for records by running a small script for comparing a few records across both data sources.</li><li>Warm up the Spanner instance with prod-like traffic before enabling the actual traffic.</li><li>Start consuming records from the CDC queue which is capturing writes from the original database, and write those to Spanner.</li><li>Before enabling write traffic on Spanner, make sure that you have started capturing writes from Spanner (Reverse CDC queue) so that they can be propagated to the existing database, so as to roll back to the original source, just in case something goes wrong.</li><li>If everything looks good, start enabling traffic to Spanner from the application in a stepwise manner.</li><li>Once direct traffic to the existing database has stopped, stop capturing writes from the original source.</li><li>Start consuming records from the Reverse CDC queue which will propagate writes from Spanner to the existing database.</li><li>Let the Reverse CDC run for a few days until everything looks stable.</li></ol><h4>Key Takeaways</h4><p>Whatever approach you take for migration, do keep these things in mind:</p><ol><li>Try to avoid manual steps in the process as much as possible to avoid any chances of errors due to human intervention.</li><li>Do test the entire migration pipeline with prod-like scenarios before the actual migration. This includes dump and restore, CDC and reverse CDC.</li><li>The schema might be different between the source and the destination Spanner database. Columns might be skipped from migration, data types conversions, splitting of data to multiple tables, etc. All of these need to be taken care of in the pipeline — bulk import, CDC and reverse CDC.</li><li>Avoid a lot of changes in the existing database during the migration phase. But still, there will be a few schema changes like new column additions, column alterations, etc during the entire migration phase. Keep these changes also in sync with the migration pipeline to avoid last-minute confusion.</li><li>At any point, the existing database should be kept in sync with the new updates (original schema/structure), at least for a few days after the migration, just in case you need to roll back.</li><li>Before enabling prod traffic on Spanner, make sure to warm up the spanner instance for about an hour with prod-like traffic. This is required to ensure that enough splits are created and data is balanced across the splits. Your existing Load testing setup at the time of POC would come in handy here.</li><li>Data validation is of utmost importance. Keep some scripts ready to validate data in both sources after the bulk restore, CDC records, and reverse CDC records. If something gets missed in validation, there is no going back, as it will be too late once we realise any discrepancy later.</li><li>Either validate records on the basis of record counts or if a more critical use case, then you may consider cell-level validation strategies as well. For the record count validation strategy, manually check a few records as well just to be sure.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9X1rzR9cCkyM--XIRNNFjw.png" /></figure><h3>Cloud Spanner is in production — now what?</h3><p>Only the migration activity has been completed, the entire task hasn’t.<br>And it can’t be completed without monitoring your Spanner instances for any issues.</p><h3>Instance and Database monitoring</h3><p>Cloud Spanner provides a very helpful monitoring view at both instance and database levels. It provides basic graphs for checking CPU usage, throughput, latencies, and storage.</p><p>While this default dashboard is more than enough in most cases, for deep diving into other metrics, you can use the Metrics explorer section under Monitoring on the Google Cloud console to get all the other Spanner metrics required for checking the state of the instances and databases.</p><p>You can also create alerts on any of the Spanner metrics as per your requirements.</p><h3>Avoid over-provisioning by enabling autoscaling</h3><p>It’s human nature to over-provision by a bit during the initial phase, to avoid any issue just after the migration, and to provide headroom for sudden spikes in traffic.</p><p>But in the longer run, this can lead to increased costs, especially if we are not downscaling during the off-peak hours — this is just a waste of resources.</p><p>For avoiding this, you can consider enabling autoscaling of the Spanner instance — after a few days of monitoring and when everything seems stable enough.</p><p>Although enabling autoscaling of Spanner instances is not straightforward like turning on a config, it is not that hard also. The spanner team has provided a detailed doc for the same which you can refer to.</p><p><a href="https://cloud.google.com/architecture/autoscaling-cloud-spanner">Autoscaling Cloud Spanner | Cloud Architecture Center | Google Cloud</a></p><h3>Key Visualiser</h3><p>This is a great tool provided by Spanner to check the read/write access patterns of keys across the entire database. This can prove to be a lot helpful in detecting hotspots, and finding which key ranges are causing hotspots.</p><p>Ideally, you should have already used this during the POC phase while running load tests.</p><p>Just for reference, sharing a screenshot of our POC phase where we used Key Visualiser to find and eliminate hotspots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lyrzpq8Caf_VCHTZnH3MaA.png" /><figcaption>We can clearly see that some key ranges are being accessed more frequently than others, causing hotspots</figcaption></figure><p>After inspecting this, we realized that there was some issue with our load generator and we were not distributing the load evenly across the records. (Ideally, this should not be the case on Prod, but you never know)</p><p>After fixing this, we got a really different state altogether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRE3fazjxsOac4CAxJGypw.png" /></figure><p>So in short, this is a great tool to have in your arsenal for monitoring Cloud Spanner.</p><h3>Introspection Tables</h3><p>Sometimes you get stuck in weird issues, which are not directly visible in the Monitoring graphs or the Key visualiser, and need to debug more on the query performance part.</p><p>For this, Spanner has some tables in the SPANNER_SYS database on the instance level, which you can use to check various details of the Spanner instance.</p><p>You can investigate issues with query stats, check top N queries in various intervals, current and oldest running queries, lock stats, read, write and transaction stats. These are individual tables which provide a lot of details which can be quite helpful in debugging a lot of tricky issues.</p><p>You can read more about these here.</p><p><a href="https://cloud.google.com/spanner/docs/introspection">Overview of introspection tools | Cloud Spanner | Google Cloud</a></p><h3>Other tools to check</h3><ol><li>Spanner provides a detailed query execution plan for any query you run. Experiment with a few queries on the query section of the Spanner console.</li><li>Query Insights — Detect and analyze query performance problems.</li><li>Lock Insights — View the lock wait time in an instance or a selected database.</li><li>Transaction insights — View the latency in transactions on an instance or a selected database.</li><li>The above 3 insights tools are launched recently, but I find them quite useful in monitoring the state of the Spanner instances and databases.</li></ol><h3>Change Streams</h3><p>Once you migrated your existing databases to Cloud Spanner, you think that your job is done as your applications are running smoothly.</p><p>But most of the time, we forget that there might be some other non-user-facing tasks that were running previously with the existing database — like some regular backup jobs, or some other Data pipelines that were being used for sending reports or powering various dashboards.</p><p>These also need to be migrated to read from the new source, i.e. Cloud Spanner.</p><p>Change streams can be a useful tool to power those backup jobs or data pipelines.</p><p>Check out more details on the same here.</p><p><a href="https://cloud.google.com/spanner/docs/change-streams">About change streams | Cloud Spanner | Google Cloud</a></p><h3>Schema Change Management</h3><p>Database evolves as the business grows.</p><p>The database never stays constant for long. There will be changes to the schema that you decided on before starting the migration. New requirements will come up, which will lead to the addition of new tables, new columns, etc.</p><p>The best part of Spanner is that in most cases of schema updates, the live traffic does not get impacted, well except for a few obviously.</p><p>Of course, there are best practices for that as well. Do check them out here.</p><p><a href="https://cloud.google.com/spanner/docs/schema-updates#best-practices">Make schema updates | Cloud Spanner | Google Cloud</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4XKTKfycATOjlxK8k2xpg.png" /></figure><p>Finally, we can say that the migration activities of our databases to Cloud Spanner are officially done.</p><p>Do keep in mind all of these while considering migrating to Cloud Spanner.</p><p>Also, please post in the comments if you want us to do a deep dive on any of the above-mentioned sections.</p><p>Until next time.</p><p>Keep evolving, keep growing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a315427796f" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/migrating-to-google-cloud-spanner-2a315427796f">Migrating to Google Cloud Spanner</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Logging essentials with EFK — Elasticsearch Fluentbit Kibana]]></title>
            <link>https://engg.glance.com/kubernetes-logging-essentials-with-efk-elasticsearch-fluentbit-kibana-99fd5efac188?source=rss-8fb52a033356------2</link>
            <guid isPermaLink="false">https://medium.com/p/99fd5efac188</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[efk]]></category>
            <category><![CDATA[fluentbit]]></category>
            <dc:creator><![CDATA[Hardik Taluja]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 05:27:09 GMT</pubDate>
            <atom:updated>2022-11-14T11:26:52.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes Logging essentials with EFK — Elasticsearch Fluentbit Kibana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9639uVoflllxnEHN" /><figcaption>Photo by <a href="https://unsplash.com/@squareddesign?utm_source=medium&amp;utm_medium=referral">Robert Larsson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Logging is an essential part of any application. Most of the time while developing any feature, we add log statements in code as per our requirements, so that we can come and check them later whenever there is any ongoing issue.</p><p>For smaller apps with lower traffic, checking logs is not much of an issue.<br>Let’s say that the application is running inside a docker container on a Pod in a small Kubernetes cluster in the form of deployment, and is putting logs to the stdout from the app.<br>Getting logs is as easy as running this <strong>kubectl</strong> command:</p><pre>kubectl logs &lt;pod_name&gt;</pre><p>And it will start printing whatever logs that are present for the default container inside that pod.</p><p>But let’s face it, applications nowadays grow at a very fast pace, and most of the apps today are spanned across multiple microservices — each of the services scaled independently across multiple instances to handle the demanding traffic.<br>Here it becomes a challenge to check logs and identify issues because we ourselves are not sure where the issue could be. We can’t be running the above command on each and every pod, that too for multiple services — that just isn’t practical to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*etx9Rd5C7EysakULcWNGxQ.gif" /></figure><p>So, we definitely need a proper mechanism for handling logs, such that we are able to find whatever we need when the time arises, easily and in a fast manner.</p><h3>Assumptions</h3><p>Sorry if we are already too late for this, but this article goes on the assumption that you are working on an awesome product that has huge demand. There are multiple teams that contribute to the growth of that product, and they work independently on individual components, and that too in different programming languages.</p><p>Each of the components has different demand and scaling requirements, which is why you have adopted the microservices architecture and are running (or planning to run) your services in a Kubernetes environment spread across multiple container-based deployments.</p><h3>Requirements</h3><p>So with these assumptions, we require a few things from you before going forward:</p><ol><li>A Kubernetes cluster that is already up and running</li><li>Multiple applications onboarded on that cluster in the form of deployment/statefulset</li><li>A fair idea of container-based applications in the K8s environment, which you already have because of points 1 and 2 ;)</li><li>Your applications are deployed on K8s using Helm charts, if not, then I am confident you can figure that out, as we would be focussing on a solution using Helm charts</li><li>Deployed applications are pushing logs either to some logs files or to the standard output, i.e. STDOUT</li><li>Frequent use cases in which log checking is required, and the command mentioned earlier seems like a pain</li></ol><p>That’s mostly it. So let’s proceed.</p><h3>Objective</h3><p>Before checking this out, let’s go through the problem once again.</p><blockquote>We don’t want to check the logs of each and every pod. Pods are mean, they come and go very frequently, and the logs go away with them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*hfoifxHEXLuGgX5DgP00UQ.gif" /></figure><p><strong>You</strong> — There’s gotta be a better way 😭<br><strong>Me</strong> — And there is Kevin!</p><p>If you don’t know who Kevin is, please stop reading here, and watch F.R.I.E.N.D.S. first.</p><p>Resume once you have watched till you know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*1pwlZSlaRWGXTas86raUZw.gif" /></figure><p>Hoping that you know now :)</p><p>Now imagine a solution that will continuously ship all the logs to a central place, and a centralized view on top of it, so that we can get the logs on-demand — quickly and efficiently, without any extra work on our part (well not so much)</p><p>For this, we will be using the EFK stack as our savior.</p><p>So, the objective of the remaining portion of this article would be to check out the EFK Stack (Elasticsearch Fluentbit Kibana) and understand how we can configure the same so that our day-to-day logging needs are met easily and efficiently.</p><h4>Why should I read this instead of others?</h4><p>I know you might be thinking that there are already tons of articles for this, but most of them just go through the setup part, missing some of the extra configs needed after the setup that will make your life easier.<br>There are genuine use cases that almost everyone needs, but are hard to figure out.</p><p>Trust me, I have been there — had to check on extra articles, official product docs, existing and ongoing GitHub issues, and even a lot of hits and trials to get the final customized solution.</p><p>So, this blog will try to cover almost all of them in a single place.</p><p>Convinced?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*UAJAuZBV7fO1UtBs.gif" /></figure><p>Great, Let’s begin.</p><h3>What is the EFK Stack?</h3><p>Well, as already mentioned above</p><blockquote>EFK stack is a solution that will continuously ship all the logs to a central place, and a centralized view on top of it, so that we can get the logs on-demand — quickly and efficiently</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*BG9GHgDnSxHcQYnWBIwP7g.png" /></figure><p><strong>Elasticsearch</strong> — NoSQL database based on the Lucene search engine. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents.</p><p><a href="https://www.elastic.co/elasticsearch/">Elasticsearch: The Official Distributed Search &amp; Analytics Engine | Elastic</a></p><p><strong>Fluentbit</strong> — Super fast, lightweight, and highly scalable logging and metrics processor and forwarder.</p><p><a href="https://fluentbit.io/">fluentbit</a></p><p><strong>Kibana</strong> — Data visualization dashboard software for Elasticsearch.</p><p><a href="https://www.elastic.co/kibana/">Kibana: Explore, Visualize, Discover Data | Elastic</a></p><p>To cover the functionality of the EFK stack as a whole:<br>Fluentbit will read the logs from the application container log files present on the nodes and will push these logs to Elasticsearch, and then Kibana will be used as a visualization tool (assume UI for now) for checking those logs.</p><h4>A bit more detail please? Some visuals might also help</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCdiJiSf3NCndLEfxZkrCA.png" /></figure><p><strong>Me</strong> — Got it now?<br><strong>You</strong> — Hmm somewhat 🤔<br><strong>Me</strong> — Okay, let me put it in some more detail then</p><ol><li>Your applications are running on the Kubernetes cluster</li><li>The cluster will have multiple nodes on which your pods will be distributed</li><li>Applications will be pushing logs on the container STDOUT, or in some log files</li><li>Here comes Fluentbit, deployed as a DaemonSet (one pod on each node)</li><li>You have asked Fluentbit to keep on listening to the logs that are relevant</li><li>Fluentbit now has the responsibility to push these logs to Elasticsearch, deployed as a StatefulSet (ordered replicas — stable storage with PVCs)</li><li>Now Elasticsearch has the responsibility of storing and indexing your logs so that you can search fast and easily and whenever you want to check the logs</li><li>And finally, Kibana would be the tool that will be used to check the logs, create custom dashboards, and even customize and monitor your deployed ES cluster</li></ol><p><strong>Me</strong> — Please tell me you got it 😌<br><strong>You</strong> — Yup, got it now<br><strong>You</strong> — But, what about Prometheus and Grafana that are also in the diagram? 😒<br><strong>Me</strong> — Those are the extras that I mentioned earlier. Don’t you need to monitor what’s going on with your shipper?<br><strong>You</strong> — Of course, we need to monitor<br><strong>Me</strong> — You see now — these are the essential things that are really needed, but not covered in other articles<br><strong>You</strong> — But this will be part of the setup only. You mentioned some extra configs too<br><strong>Me</strong> — Yes there will be, we’ll circle back to monitoring and extra configs in a while<br><strong>You</strong> — Okay</p><h4>Why Fluentbit only? And not others?</h4><p>Yes, there are multiple other tools that can be used for the same purpose, like Logstash, Fluentd, Filebeat, etc.<br>But we are preferring Fluentbit here as it provides all the functionality we need for our logging use case, plus it is really lightweight with great performance and is built on top of the best ideas of Fluentd architecture and general design.</p><p>Sharing the difference between Fluentd and Fluentbit as per the official docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xJgWUe3BlS1ttgO5viDfg.png" /><figcaption>Source: <a href="https://docs.fluentbit.io/manual/about/fluentd-and-fluent-bit">Fluentbit docs</a></figcaption></figure><h3>Seems good, how can I start using it?</h3><p>Remember I asked you to be familiar with Helm charts?</p><p>Don’t worry if you are not aware of those — Helm is a package manager for Kubernetes which uses a packaging format called charts. A chart is a collection of manifest files that describe a related set of Kubernetes resources. Here are a ton of details on the same.</p><p><a href="https://helm.sh/docs/topics/charts/">Charts</a></p><p>Now, we would be deploying the EFK stack on the Kubernetes cluster using Helm Charts for each of them to avoid the manual work of creating the individual Kubernetes resources. By default, the helm release will pick chart variable values from the default values.yaml (we can override with a new values file, or can update the properties in the same values file as well)</p><p>We would be using the below Helm charts:</p><ul><li><a href="https://github.com/elastic/helm-charts">GitHub - elastic/helm-charts: You know, for Kubernetes</a></li><li><a href="https://github.com/fluent/helm-charts">GitHub - fluent/helm-charts: Helm Charts for Fluentd and Fluent Bit</a></li></ul><ol><li>For Elasticsearch and Kibana. The latest chart version present at the time of writing is available <a href="https://github.com/elastic/helm-charts/releases/tag/v7.17.3">here</a></li><li>For Fluentbit. The latest chart version present at the time of writing is available <a href="https://github.com/fluent/helm-charts/releases/tag/fluent-bit-0.20.5">here</a></li></ol><h4>Charts Installation</h4><p>If you are using any existing tool for managing helm chart deployments, like FluxCD or ArgoCD, etc, then you might already have some set mechanism for adding new Helm Releases. You can go ahead and similarly add these 3 new releases in a separate k8s namespace, specifying the official helm charts repository and their versions, with custom values.yaml file (if any changes are required to the default values)</p><h4>Manual Installation</h4><p>If not, then you can go ahead with the manual installation of these charts. Just download the latest stable chart version from the links provided above, and extract them to a folder, say ~/efk.</p><p>Run the following commands:</p><p>Create a k8s namespace for deploying the stack</p><pre>kubectl create namespace efk</pre><p>Go to the extracted charts directories and install the helm charts in the newly created namespace. But before that, a few changes are suggested to the existing values.yaml files, so that you can validate the setup easily.</p><p>In both Elasticsearch and Kibana <strong>values.yaml</strong> files, update the service type from ClusterIP to LoadBalancer (on Prod, you might want to check ingress).</p><pre>~/efk/helm-charts-7.17.3/elasticsearch/values.yaml<br>~/efk/helm-charts-7.17.3/elasticsearch/kibana.yaml</pre><p>Change this:</p><pre>service:<br>  ...<br>  ...<br>  ...<br>  type: ClusterIP<br>  ...<br>  ...</pre><p>to</p><pre>service:<br>  ...<br>  ...<br>  ...<br>  type: LoadBalancer<br>  ...<br>  ...</pre><p>Now we can go ahead with the installation of the helm charts.</p><pre>cd ~/efk/helm-charts-7.17.3/elasticsearch<br>helm install --namespace efk --name elasticsearch .<br><br>cd ~/efk/helm-charts-7.17.3/kibana<br>helm install --namespace efk --name kibana .<br><br>cd ~/efk/fluent-bit<br>helm install --namespace efk --name fluent-bit .</pre><p>And that’s it, the EFK stack is up and running with the default set of values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*sNIsDTbhquccbX0l14j7Gw.gif" /></figure><h4>Verification</h4><p>You can verify the same by running the following commands:</p><pre>kubectl get pods</pre><p>You should be able to see 3 Elasticsearch pods and 1 Kibana pod<br>The number of pods for Fluentbit will depend on the number of nodes present on the cluster.</p><p>Also, you can verify that the Fluentbit runs as a Daemonset, Elasticsearch as a Statefulset, and Kibana as a deployment by running the following commands:</p><pre>kubectl get daemonset<br>kubectl get statefulset<br>kubectl get deployment</pre><p>Now, for checking ES and Kibana, you can get the LB IPs from the external IP section in the output of the following command</p><pre>kubectl get service</pre><p>For ES, can paste the LB_IP in a browser, and you should get a JSON output specifying some cluster details, something similar to this:<br>If not, then try with LB_IP:9200</p><pre>{<br>  &quot;name&quot; : &quot;&lt;pod_name_that_received_the_request&gt;&quot;,<br>  &quot;cluster_name&quot; : &quot;elasticsearch&quot;,<br>  &quot;cluster_uuid&quot; : &quot;&lt;some_id&gt;&quot;,<br>  &quot;version&quot; : {<br>    &quot;number&quot; : &quot;&lt;es_version_deployed&gt;&quot;,<br>    &quot;build_flavor&quot; : &quot;default&quot;,<br>    &quot;build_type&quot; : &quot;docker&quot;,<br>    &quot;build_hash&quot; : &quot;&lt;some_hash&gt;&quot;,<br>    &quot;build_date&quot; : &quot;&lt;some_date&gt;&quot;,<br>    &quot;build_snapshot&quot; : false,<br>    ...<br>    ...<br>    ...<br>  },<br>  &quot;tagline&quot; : &quot;You Know, for Search&quot;<br>}</pre><p>Similarly for Kibana, you can use the LB_IP in a browser, you should see the Kibana UI that you can use for exploring logs as well as the ES cluster. UI should be similar to this:<br>If not, then try with LB_IP:5601</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onEzcMBWNiCl6D6dCRzN_A.png" /></figure><h4>Exploration</h4><p>By default, Fluentbit will start gathering container logs from all the pods that are present in the cluster and will push these to the newly deployed ES cluster.</p><p>It also listens to the systemd metrics and pushes them to the same ES cluster.</p><p>For exploring the logs, first, verify whether the newly created indices are showing on Kibana.<br>Go to Kibana → Stack Management → Index Management, and under the Indices tab, you should see the 2 newly created indices with the names logstash-yyyy.MM.dd and node-yyyy.MM.dd</p><p>For checking your application logs on Kibana, you need to create an Index Pattern for your app (one-time activity).</p><ol><li>Index patterns can be created by: Go to Kibana → Stack Management → Index Patterns → Create Index Pattern → Specify your index pattern and select a timestamp field → Done</li><li>Now, you can check your logs by going to Discover → Select your newly created index pattern from the dropdown → Search Logs</li></ol><p>And we are done. At this point, we can say that our setup is complete, and is ready to use for all our logging needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*m7OkigCanmWF8ZnnKUdDcg.gif" /></figure><h3>Wait, aren’t you forgetting something? 😏</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*tvRFoyBxEPmxy3G2VAqLCg.gif" /></figure><p>Okay, let’s cover the extra setup and config part.</p><p>Well, it’s not all config, there are some extra things that I want to share that made my life easier while dealing with a lot of applications and log volumes.</p><p>So, let’s try to check them one by one.</p><h4>Application Logging Format</h4><p>There are a lot of ways in which applications print their logs — depending on the logging libraries, the programming language, or the framework.</p><p><strong>You</strong> — Why are we talking about logging formats all of a sudden?<br><strong>Me</strong> — Because it will help you choose a standard across all your applications, and even allow you to add custom parameters in the log events as per requirements.</p><p>You can use JSON logging so that your application itself will produce logs in JSON format.</p><p><strong>You</strong> — Any benefits?<br><strong>Me</strong> — Definitely</p><ol><li>Fluentbit will read the entire JSON log line as a single event and will push it to ES (ES stores logs as JSON documents, so…)</li><li>You don’t have to worry about parsing the single-line log events and identifying and mapping all params that are present in the log</li><li>Exceptions — Oh man! those stack traces. I can’t tell you how frustrated I got upon seeing the multi-line stack traces getting spanned to multiple log events in ES — there goes our debugging (Have tried with multi-line parsers in Fluentbit, but it is still a pain)</li><li>You can add custom key-value pairs in the log event itself, and they will get added to the ES document, on which you can search, aggregate, or even create custom dashboards as per your needs.</li></ol><p><strong>You</strong> — Nice, I’m in. What all changes are needed?<br><strong>Me</strong> — For now, I am assuming that you are using Java Spring/Spring Boot for your app development, and you are using Logback XML-based config for logs.<br><strong>You</strong> — No worries, I will figure it out for others, you go on.</p><p>This dependency is required for the Logback Logstash Encoder which will help in generating JSON logs. Add this to your <strong>pom.xml</strong> file.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;net.logstash.logback&lt;/groupId&gt;<br>  &lt;artifactId&gt;logstash-logback-encoder&lt;/artifactId&gt;<br>  &lt;version&gt;5.2&lt;/version&gt;<br>  &lt;!--You can check the latest version available when you are using--&gt;<br>&lt;/dependency&gt;</pre><p>Use this appender for your logs which will put JSON logs to your console. Add this to your <strong>logback.xml</strong> config file.</p><pre>&lt;appender name=&quot;jsonComposite&quot; class=&quot;ch.qos.logback.core.ConsoleAppender&quot;&gt;<br>  &lt;encoder class=&quot;net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder&quot;&gt;<br>    &lt;providers&gt;<br>      &lt;pattern&gt;<br>        &lt;pattern&gt;<br>          {<br>            &quot;timestamp&quot;: &quot;%date&quot;,<br>            &quot;thread&quot;: &quot;%thread&quot;,<br>            &quot;level&quot;: &quot;%level&quot;,<br>            &quot;logger&quot;: &quot;%logger&quot;,<br>            &quot;message&quot;: &quot;%message&quot;<br>          }<br>        &lt;/pattern&gt;<br>      &lt;/pattern&gt;<br>      &lt;mdc/&gt;<br>      &lt;arguments/&gt;<br>      &lt;stackTrace&gt;<br>        &lt;throwableConverter class=&quot;net.logstash.logback.stacktrace.ShortenedThrowableConverter&quot;&gt;<br>          &lt;maxDepthPerThrowable&gt;30&lt;/maxDepthPerThrowable&gt;<br>          &lt;maxLength&gt;2048&lt;/maxLength&gt;<br>          &lt;shortenedClassNameLength&gt;20&lt;/shortenedClassNameLength&gt;<br>          &lt;exclude&gt;^sun\.reflect\..*\.invoke&lt;/exclude&gt;<br>          &lt;exclude&gt;^net\.sf\.cglib\.proxy\.MethodProxy\.invoke&lt;/exclude&gt;<br>          &lt;rootCauseFirst&gt;true&lt;/rootCauseFirst&gt;<br>        &lt;/throwableConverter&gt;<br>      &lt;/stackTrace&gt;<br>    &lt;/providers&gt;<br>  &lt;/encoder&gt;<br>&lt;/appender&gt;<br><br>&lt;root level=&quot;INFO&quot;&gt;<br>&lt;appender-ref ref=&quot;jsonComposite&quot;/&gt;<br>&lt;/root&gt;</pre><p>You can customize this however you like — not covering everything here. You can check this in more detail here:</p><p><a href="https://github.com/logfellow/logstash-logback-encoder">GitHub - logfellow/logstash-logback-encoder: Logback JSON encoder and appenders</a></p><h4>Separate ES index per application</h4><p><strong>Me</strong> — Did you see the Fluentbit config file?<br><strong>You</strong> — Let me check</p><p>It’s something like this:</p><pre>...<br>...<br>...<br>config:<br>  service: |<br>    [SERVICE]<br>        Daemon Off<br>        Flush {{ .Values.flush }}<br>        Log_Level {{ .Values.logLevel }}<br>        Parsers_File parsers.conf<br>        Parsers_File custom_parsers.conf<br>        HTTP_Server On<br>        HTTP_Listen 0.0.0.0<br>        HTTP_Port {{ .Values.metricsPort }}<br>        Health_Check On<br><br>  inputs: |<br>    [INPUT]<br>        Name tail<br>        Path /var/log/containers/*.log<br>        multiline.parser docker, cri<br>        Tag kube.*<br>        Mem_Buf_Limit 5MB<br>        Skip_Long_Lines On<br><br>  filters: |<br>    [FILTER]<br>        Name kubernetes<br>        Match kube.*<br>        Merge_Log On<br>        Keep_Log Off<br>        K8S-Logging.Parser On<br>        K8S-Logging.Exclude On<br><br>  ## https://docs.fluentbit.io/manual/pipeline/outputs<br>  outputs: |<br>    [OUTPUT]<br>        Name es<br>        Match kube.*<br>        Host elasticsearch-master<br>        Logstash_Format On<br>        Retry_Limit False<br>...<br>...<br>...</pre><p>This is the line in the config that is responsible for reading all the container logs:</p><pre>Path /var/log/containers/*.log</pre><p><strong>Me</strong> — You might have noticed by now that logs from all apps are going in the same ES index (We didn’t specify any, but it goes into a single index by default)<br><strong>You</strong> — Yeah, so? Doesn’t seem like a problem<br><strong>Me</strong> — Are you sure that all your teams are going to follow the above log format?<br><strong>You</strong> — Wouldn’t bet on it<br><strong>Me</strong> — Great, then this would be helpful</p><p>Having a single index doesn’t seem like an issue at first. But if multiple applications start following their own log formats, then there is some collision bound to happen sooner or later.</p><blockquote>Enforcing a fixed logging format across teams is hard</blockquote><p>Logs will go to ES as JSON docs, and ES maintains a mapping for each index. So, if you are using a single index, then if any new document comes with a field with the same name, but if the type is different than what is already saved in the index field mapping, then those log events will get dropped.</p><p><strong>You</strong> — Fair point, but I don’t want to put separate Input Output config pairs for all my applications 😢<br><strong>Me</strong> — You don’t need to, luckily there is a better solution</p><p>We can use a Lua script and a simple Lua filter for adding the index field in the log event itself and then use that field in the output plugin in the Logstash_Prefix_Key</p><pre>...<br>...<br>...<br>luaScripts:<br>  setIndex.lua: |<br>    function set_index(tag, timestamp, record)<br>        index = &quot;somePrefix-&quot;<br>        if record[&quot;kubernetes&quot;] ~= nil then<br>            if record[&quot;kubernetes&quot;][&quot;namespace_name&quot;] ~= nil then<br>                if record[&quot;kubernetes&quot;][&quot;container_name&quot;] ~= nil then<br>                    record[&quot;es_index&quot;] = index<br>                        .. record[&quot;kubernetes&quot;][&quot;namespace_name&quot;]<br>                        .. &quot;-&quot;<br>                        .. record[&quot;kubernetes&quot;][&quot;container_name&quot;]<br>                    return 1, timestamp, record<br>                end<br>                record[&quot;es_index&quot;] = index<br>                    .. record[&quot;kubernetes&quot;][&quot;namespace_name&quot;]<br>                return 1, timestamp, record<br>            end<br>        end<br>        return 1, timestamp, record<br>    end<br>config:<br>  service: |<br>  ...<br>  ...<br>  inputs: |<br>    [INPUT]<br>        Name tail<br>        Path /var/log/containers/*.log<br>        multiline.parser docker, cri<br>        Tag kube.*<br>        Mem_Buf_Limit 5MB<br>        Skip_Long_Lines On<br>  filters: |<br>    [FILTER]<br>        Name kubernetes<br>        Match kube.*<br>        Merge_Log On<br>        Keep_Log Off<br>        K8S-Logging.Parser On<br>        K8S-Logging.Exclude On<br>    [FILTER]<br>        Name lua<br>        Match kube.*<br>        script /fluent-bit/scripts/setIndex.lua<br>        call set_index<br>  outputs: |<br>    [OUTPUT]<br>        Name es<br>        Match kube.*<br>        Host elasticsearch-master<br>        Logstash_Format On<br>        Logstash_Prefix applogs # used in case prefix key is absent<br>        Logstash_Prefix_Key es_index<br>        Retry_Limit False<br>...<br>...</pre><p>Now, let’s see what this script and filter are doing.</p><p>Nothing much, we specify a dynamic ES output index in each of the log events. As per this script, this format is being used for the index name:</p><pre>somePrefix-{k8s_namespace_name}-{container_name}-{Date}<br><br>Like:<br>somePrefix-auth-user-service-2022-08-21<br>somePrefix-product-catalog-service-2022-08-22<br>... and so on</pre><p>And this somePrefix can be your company name, or whatever you like. You can choose a different format as well — just need to change the script, that’s all.</p><h4>Kubernetes metadata in logs</h4><p><strong>Me</strong> — Wouldn’t it be great if you can get details like annotations, labels, and other pod and container info in logs?<br><strong>You</strong> — Great, more work 😒<br><strong>Me</strong> — Guess what, it is already a part of the default Fluenbit config. Check out this part of the values.yaml file</p><pre>...<br>...<br>  filters: |<br>    [FILTER]<br>        Name kubernetes<br>        Match kube.*<br>        Merge_Log On<br>        Keep_Log Off<br>        K8S-Logging.Parser On<br>        K8S-Logging.Exclude On<br>...<br>...</pre><p><strong>You</strong> — If it was already present, then why bother?<br><strong>Me</strong> — Just a friendly reminder so that you don’t forget while moving away from the default config to a custom one 😇</p><p><strong>Me</strong> — There are a lot of options to configure here as well 🤫 You know where to find them.</p><h4>There will be a lot of logs — A LOT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*mX2K4GHHV9T51TlwD_rXlw.gif" /></figure><p>Well, I will not tell you how much ES cluster size you should have for storing logs — that is up to you to figure out as per your use case.</p><p>But whatever you finalize, there will be a lot of logs, and it is important that you dump off older logs when not needed.</p><p>Luckily, we have ILM Policies in ES to help us with this.</p><p>You can specify a single ILM policy for all your indices, or you can choose a different one for all of them, but a basic Deletion policy is a must. Or if there are any compliance requirements to keep the logs for longer durations, you can check out backup options as well. But for now, let’s check how to apply a single ILM policy for all the indices.</p><p>You need to create the ILM policy first — you can do it via the UI, from the Dev Tools (both from Kibana UI), or by sending a curl request to the ES endpoint.</p><p>I will share the request here for having a retention policy with 1-day Hot Phase, then a 3-day Warm Phase, and finally a Delete Phase.</p><p>This can serve as a default Policy for all the log indices.</p><pre>PUT _ilm/policy/retention-3day<br>{<br>  &quot;policy&quot;: {<br>    &quot;phases&quot;: {<br>      &quot;hot&quot;: {<br>        &quot;min_age&quot;: &quot;0ms&quot;,<br>        &quot;actions&quot;: {<br>          &quot;rollover&quot;: {<br>            &quot;max_primary_shard_size&quot;: &quot;50gb&quot;,<br>            &quot;max_age&quot;: &quot;1d&quot;<br>          },<br>          &quot;set_priority&quot;: {<br>            &quot;priority&quot;: 100<br>          }<br>        }<br>      },<br>      &quot;warm&quot;: {<br>        &quot;min_age&quot;: &quot;1d&quot;,<br>        &quot;actions&quot;: {<br>          &quot;forcemerge&quot;: {<br>            &quot;max_num_segments&quot;: 2<br>          },<br>          &quot;shrink&quot;: {<br>            &quot;number_of_shards&quot;: 1<br>          }<br>        }<br>      },<br>      &quot;delete&quot;: {<br>        &quot;min_age&quot;: &quot;3d&quot;,<br>        &quot;actions&quot;: {<br>          &quot;delete&quot;: {<br>            &quot;delete_searchable_snapshot&quot;: true<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>There is a Cold Phase as well which you can check, plus you can figure out the parameters as per your requirement.</p><p>Now that the ILM policy is created, you need to apply this to all your indices.</p><p>For that, first, we need a component template (partial settings that you can apply to multiple index templates).</p><pre>PUT _component_template/3day-lifecyle-settings<br>{<br>  &quot;template&quot;: {<br>    &quot;settings&quot;: {<br>      &quot;index&quot;: {<br>        &quot;lifecycle&quot;: {<br>          &quot;name&quot;: &quot;retention-3day&quot;<br>        }<br>      }<br>    }<br>  },<br>  &quot;_meta&quot;: {<br>    &quot;description&quot;: &quot;Settings for ILM&quot;<br>  }<br>}</pre><p>Then, finally, we need to create the index template specifying this component template.</p><pre>PUT _index_template/applogs-template<br>{<br>  &quot;index_patterns&quot;: [<br>    &quot;somePrefix*&quot;<br>  ],<br>  &quot;composed_of&quot;: [<br>    &quot;3day-lifecyle-settings&quot;<br>  ],<br>  &quot;priority&quot;: 500,<br>  &quot;_meta&quot;: {<br>    &quot;description&quot;: &quot;Template for all app logs&quot;<br>  },<br>  &quot;data_stream&quot;: {<br>    &quot;hidden&quot;: false<br>  }<br>}</pre><p>Here, we used the <strong>somePrefix</strong> that we added earlier to all the indices so that the ILM policy can be applied to all the indices at once.</p><p>You can configure different ILM policies for different indices as well. Just need to create another one with a different priority.</p><p><strong>You</strong> — I get it that there will be a lot of logs, and we need to discard the old ones.<br><strong>You</strong> — But I am getting so many logs because Fluentbit is sending all container logs. I don’t want all of them.<br><strong>Me</strong> — Only if you had waited some more, I was coming to it next.<br><strong>You</strong> — Oops, sorry 😅</p><h4>You don’t need all the logs</h4><p>As you have already noticed that Fluentbit is sending all the container logs to your Elasticsearch instance.</p><p>Because of this:</p><pre>...<br>...<br>config:<br>  service: |<br>  ...<br>  ...<br>  inputs: |<br>    [INPUT]<br>        Name tail<br>        Path /var/log/containers/*.log<br>        multiline.parser docker, cri<br>        Tag kube.*<br>        Mem_Buf_Limit 5MB<br>        Skip_Long_Lines On<br>...<br>...</pre><p>But you can have fine-grained control over what logs Fluenbit has to listen to.</p><p>You can specify comma-separated Path patterns in the Path variable.</p><p>Or, you can have separate INPUT plugins for each application, and specify an Alias for each of the INPUT. This way you will be able to monitor the log volume for each of the apps separately — this Alias directly gets added to the metrics that Fluentbit emits.</p><pre>...<br>...<br>  inputs: |<br>    [INPUT]<br>        Name tail<br>        Alias fluentbit<br>        Path /var/log/containers/fluentbit*.log<br>        multiline.parser docker, cri<br>        Tag kube.*<br>        Mem_Buf_Limit 5MB<br>        Skip_Long_Lines On<br>    [INPUT]<br>        Name tail<br>        Alias user<br>        Path /var/log/containers/user*.log<br>        multiline.parser docker, cri<br>        Tag kube.*<br>        Mem_Buf_Limit 5MB<br>        Skip_Long_Lines On<br>    [INPUT]<br>        Name tail<br>        Alias catalog<br>        Path /var/log/containers/catalog*.log<br>        multiline.parser docker, cri<br>        Tag kube.*<br>        Mem_Buf_Limit 5MB<br>        Skip_Long_Lines On<br>...<br>...</pre><p><strong>You</strong> — How did you know what path to specify?<br><strong>Me</strong> — This would be the path to which your application is writing logs.<br><strong>You</strong> — But I am not specifying any log file path in my application.<br><strong>Me</strong> — Then by default your logs would be going to the STDOUT</p><p>And because the apps are running inside containers, your log path would be in this format:</p><pre>/var/log/containers/{pod_name}_{namepsace_name}_{container_name}-{container_id}.log<br>For eg:<br>/var/log/containers/catalog-service-588c6c8ccd-dljth_product_catalog-service-5174ad29667977e289442c71d9fb873b656727e2c342102cc599b911f9259159.log</pre><p>So, you can specify the pattern as</p><pre>/var/log/containers/catalog-service*.log<br>or<br>/var/log/containers/catalog*.log</pre><h4>Almost done — just need monitoring</h4><p><strong>Me</strong> — Remember you asked why Prometheus and Grafana were there in the architecture diagram?<br><strong>You</strong> — Setting it up will take a lot of time, right?<br><strong>Me</strong> — Umm, not much, but I am assuming here that you are already using Prometheus and Grafana<br><strong>You</strong> — Yes, please hurry up, I am tired of this long blog now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*6rqPbrMsP9p3ofTb9ca83Q.gif" /></figure><p><strong>Me</strong> — Don’t worry, you only need to add a few annotations</p><pre>values:<br>    service:<br>      annotations:<br>        prometheus.io/path: &quot;/api/v1/metrics/prometheus&quot;<br>        prometheus.io/port: &quot;2020&quot;<br>        prometheus.io/scrape: &quot;true&quot;<br>    luaScripts:<br>...<br>...<br>    config:<br>      service: |<br>      ...<br>      ...<br>      inputs: |<br>      ...<br>      ...<br>...<br>...</pre><p><strong>Me</strong> — With this, Prometheus will start scraping metrics from all the fluentbit pods<br><strong>You</strong> — Please let there be a ready-made dashboard for this 🥺<br><strong>Me</strong> — And there is Kevin!</p><p>Just check this out.</p><p><a href="https://grafana.com/grafana/dashboards/11620-logging-dashboard/">FluentBit | Grafana Labs</a></p><p>If you are using a different setup for monitoring, then I will leave this up to you to figure out how to do this.</p><p>For ES monitoring, Default Monitoring Dashboard at Kibana should be sufficient.</p><h3>And we are officially Done</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*k70IKWVwzeWAEvAjrlG2IA.gif" /></figure><h3>Are you sure you are not forgetting anything else?</h3><p>Hmm, let me check.</p><ul><li>Intro</li><li>Problem</li><li>Assumptions</li><li>Requirements</li><li>Objective</li><li>Architecture</li><li>Setup</li><li>App log format</li><li>Separate ES indices</li><li>K8s metadata in logs</li><li>ILM Policy</li><li>Not all logs</li><li>Monitoring</li><li>Reminder to watch F.R.I.E.N.D.S.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*V3Zh-YYT05xWljKXlaVJPw.gif" /></figure><p>Even if something’s left, it would be because</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*_dP_ZZ6fYB6nhwyaBr_AjQ.gif" /></figure><p>So keep looking for other things that you feel will be really needed for your setup, but you are having a hard time implementing them.</p><p>Do comment on those, and will try to include them as well.</p><p>Until next time.</p><p>Goodbye!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vQKxsWVZkxOEug0fQLAWKQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99fd5efac188" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/kubernetes-logging-essentials-with-efk-elasticsearch-fluentbit-kibana-99fd5efac188">Kubernetes Logging essentials with EFK — Elasticsearch Fluentbit Kibana</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>