<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>/var/log/rani</title>
    <link>https://blog.ranigiro.uk/dragonfly/</link>
    <description></description>
    <pubDate>Fri, 27 Nov 2026 14:58:38 +0200</pubDate>
    <item>
      <title>When Analog is Faster Than Digital - The Story of Biological Neural Networks</title>
      <link>https://blog.ranigiro.uk/dragonfly/when-analog-is-faster-than-digital-the-story-of-biological-neural-networks</link>
      <description>&lt;![CDATA[By: Rani Giro&#xA;an AI Generate Image of in vitro biological neural network&#xA;&#xA;Introduction&#xA;What if I told you that your skin cells can play Pong and even Doom? This is the story of Biological Neural Networks.&#xA;&#xA;More often than not, analog/biological systems are slower than digital systems with high compute throughput and blazingly fast operations. However, Biological Neural Networks are proving to be an exception. We are seeing a shift from the traditional paradigm of running biological simulations on silicon chips to performing computational tasks directly on living cells!&#xA;!--more--&#xA;What you will learn in this article&#xA;What a Biological Neural Network is&#xA;How it is harnessed to perform computation using living neuron cells&#xA;The communication protocol between a computer and a neuron&#xA;The scalability of Biological Neural Networks&#xA;Energy advantages over traditional AI systems&#xA;&#xA;So, what is a Biological Neural Network?&#xA;&#xA;A Biological Neural Network is a large, interconnected web of living nerve cells (neurons) that allows an organism to process information and respond to its environment.&#xA;&#xA;In simple terms, it is the organic &#34;wiring&#34; of stem cells (in our context) to electrodes. Using this setup, we can teach these cells to perform basically any operation our minds can do.&#xA;&#xA;blockquote class=&#34;otro-blockquote&#34;&#xA;&#34;Generalized Synthetic Biological Intelligence may arrive before artificial general intelligence (AGI) due to the inherent efficiency and evolutionary advantage of biological systems.&#34;&#xA;spanMark Buchanan, 2018/span&#xA;/blockquote&#xA;&#xA;How it works&#xA;&#xA;At first, we take a standard cell from a human (like a skin cell) or from a rodent embryo. Through a process called human-induced pluripotent stem cells (hiPSCs), we &#39;reprogram&#39; these ordinary cells into stem cells and then grow them into living neurons on top of our electrodes. These electrodes allow the neurons to communicate with an external environment, but don&#39;t worry about it for now.&#xA;&#xA;An in vitro neuronal network coupled to a multielectrode array chip.&#xA;An in vitro neuronal network coupled to a multielectrode array chip.&#xA;But, how can we talk to it?&#xA;&#xA;The Input&#xA;We &#34;stimulate&#34; the cells by sending tiny pulses of electricity through the electrodes on the chip.&#xA;&#xA;Spatial Coding: If we want the BNN to know an object is on the left in a game, we stimulate the electrodes on the left side of the dish.&#xA;&#xA;Frequency: The speed or pattern of these pulses tells the neurons the &#34;intensity&#34; of the information.&#xA;&#xA;The Output&#xA;When neurons &#34;think&#34; or react, they fire their own electrical spikes (called action potentials).&#xA;&#xA;The sensors on the chip detect these tiny voltage changes.&#xA;&#xA;A computer program &#34;decodes&#34; which neurons fired and turns that data into an action like moving a paddle in Pong or a character in Doom.&#xA;&#xA;It&#39;s important to note that we only talk via electrical stimulation. Both are on the same channel for sending and receiving, so timing is essential.&#xA;&#xA;The Act of Learning &#xA;Since neurons don&#39;t understand natural language, we &#34;talk&#34; to them using the Free Energy Principle:&#xA;&#xA;The Carrot: If the BNN does what we want (hits the ball), we send a predictable, steady signal. Neurons like this because it allows them to create a stable model of their world. In short, neurons seeks to minimize unpredictability.&#xA;&#xA;The Stick: If it misses, we blast it with random, chaotic signal. Neurons naturally try to avoid this &#34;unpredictable&#34; state, so they physically rewire themselves to repeat the actions that lead to the steady, calm signal.&#xA; &#xA;Steps to communicate with a biological neural network&#xA;a low latency closed loop feedback system demonstrating communication the game of Pong with a Biological Neural Network_&#xA;&#xA;Scalability&#xA;While scaling an Artificial Neural Network (ANN) involves buying more GPUs and using more electricity, scaling a BNN involves growing more biological tissue and keeping it alive. They are highly scalable, and there is a clear energy advantage.&#xA;&#xA;The Energy Advantage&#xA;ANNs: As you add &#34;neurons&#34; to a digital model (like GPT-4), the energy cost explodes. Massive data centers are required.&#xA;&#xA;BNNs: The human brain has 86 billion neurons but runs on only 20 watts (about the same as a dim lightbulb). Scaling a BNN from 800,000 to 80 million neurons doesn&#39;t require a power plant; it just requires a bit more &#34;sugar water&#34;.&#xA;&#xA;Conclusion: The Dawn of the Bio-Computer&#xA;The success of biological neural networks in mastering games like Pong and Doom is more than just a scientific curiosity; it is a proof of concept for a new era of Synthetic Biological Intelligence. We are moving away from simply trying to mimic the brain with code and toward partnering with it as a hardware component.&#xA;&#xA;As digital AI models grow larger, their carbon footprint becomes a global concern. BNNs offer a path toward &#34;Green AI,&#34; where complex problem-solving requires milliwatts instead of megawatts. By leveraging the Free Energy Principle, we’ve seen that biology can adapt to new environments with a speed and flexibility that digital algorithms still struggle to match.&#xA;&#xA;The story of Biological Neural Networks reminds us that while we have spent decades trying to make computers &#34;smarter,&#34; nature has already provided us with the most sophisticated, efficient, and adaptive processor in existence. The future of computing might not be found in bigger data centers, but in the incredibly fast world of the living cell.&#xA;&#xA;References&#xA;Kagan, B. J., Kitchen, A. C., Tran, N. T., Habibollahi, F., Khajehnejad, M., Parker, B. J., ... &amp; Friston, K. J. (2022). In vitro neurons learn and exhibit sentience when embodied in a simulated game-world. Neuron, 110(23), 3952-3969.&#xA;&#xA; &#xA;&#xA;---&#xD;&#xA;blockquote class=&#34;blockquote&#34;&#xD;&#xA;p&#34;Writing is how I learn; sharing is how we grow.&#34;&#xD;&#xA;I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let&#39;s build something together./p&#xD;&#xA;/blockquote&#xD;&#xA;Connect: 👥 Linkedin ⭐ Github&#xD;&#xA;&#xD;&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>By: Rani Giro
<img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/zaGa3Ncaj4w748H?file=/&amp;fileId=22302&amp;x=2100&amp;y=1312&amp;a=true&amp;etag=99cec184b95852abe9dd4fc1f99abdfc" alt="an AI Generate Image of in vitro biological neural network"></p>

<h2 id="introduction">Introduction</h2>

<p><em>What if I told you that your skin cells can play Pong and even Doom? This is the story of Biological Neural Networks.</em></p>

<p>More often than not, analog/biological systems are slower than digital systems with high compute throughput and blazingly fast operations. However, Biological Neural Networks are proving to be an exception. We are seeing a shift from the traditional paradigm of running biological simulations on silicon chips to <strong>performing computational tasks directly on living cells!</strong>
</p>

<h2 id="what-you-will-learn-in-this-article">What you will learn in this article</h2>
<ul><li>What a Biological Neural Network is</li>
<li>How it is harnessed to perform computation using living neuron cells</li>
<li>The communication protocol between a computer and a neuron</li>
<li>The scalability of Biological Neural Networks</li>
<li>Energy advantages over traditional AI systems</li></ul>

<h2 id="so-what-is-a-biological-neural-network">So, what is a Biological Neural Network?</h2>

<p>A Biological Neural Network is a large, interconnected web of living nerve cells (neurons) that allows an organism to process information and respond to its environment.</p>

<p>In simple terms, it is the <strong>organic</strong> “wiring” of stem cells (in our context) to electrodes. Using this setup, we can teach these cells to perform basically any operation our minds can do.</p>

<blockquote class="otro-blockquote">
&#34;Generalized Synthetic Biological Intelligence may arrive before artificial general intelligence (AGI) due to the inherent efficiency and evolutionary advantage of biological systems.&#34;
<span>Mark Buchanan, 2018</span></blockquote>

<h2 id="how-it-works">How it works</h2>

<p>At first, we take a standard cell from a human (like a skin cell) or from a rodent embryo. Through a process called human-induced pluripotent stem cells (hiPSCs), we &#39;reprogram&#39; these ordinary cells into stem cells and then grow them into living neurons on top of our electrodes. These electrodes allow the neurons to communicate with an external environment, but don&#39;t worry about it for now.</p>

<p><img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/GiiFQimEyCzGWpY?file=/&amp;fileId=22325&amp;x=2100&amp;y=1312&amp;a=true&amp;etag=fdf3baa8abb18b644aac35eaa3007e92" alt="An in vitro neuronal network coupled to a multielectrode array chip.">
<em>An in vitro neuronal network coupled to a multielectrode array chip.</em></p>

<h3 id="but-how-can-we-talk-to-it">But, how can we talk to it?</h3>

<h4 id="the-input">The Input</h4>

<p>We “stimulate” the cells by sending tiny pulses of electricity through the electrodes on the chip.</p>

<p><strong>Spatial Coding</strong>: If we want the BNN to know an object is on the left in a game, we stimulate the electrodes on the left side of the dish.</p>

<p><strong>Frequency</strong>: The speed or pattern of these pulses tells the neurons the “intensity” of the information.</p>

<h4 id="the-output">The Output</h4>

<p>When neurons “think” or react, they fire their own electrical spikes (called action potentials).</p>

<p>The sensors on the chip detect these tiny voltage changes.</p>

<p>A computer program “decodes” which neurons fired and turns that data into an action like moving a paddle in Pong or a character in Doom.</p>

<p>It&#39;s important to note that we only talk via electrical stimulation. Both are on the same channel for sending and receiving, so timing is essential.</p>

<h4 id="the-act-of-learning">The Act of Learning</h4>

<p>Since neurons don&#39;t understand natural language, we “talk” to them using the Free Energy Principle:</p>

<p><strong>The Carrot:</strong> If the BNN does what we want (hits the ball), we send a predictable, steady signal. Neurons like this because it allows them to create a stable model of their world. In short, neurons seeks to minimize unpredictability.</p>

<p><strong>The Stick</strong>: If it misses, we blast it with random, chaotic signal. Neurons naturally try to avoid this “unpredictable” state, so they physically rewire themselves to repeat the actions that lead to the steady, calm signal.</p>

<p><img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/JekSHJDEc33xx4A?file=/&amp;fileId=22314&amp;x=2100&amp;y=1312&amp;a=true&amp;etag=dc115ebf97a37228d9ca94ff5868a6e0" alt="Steps to communicate with a biological neural network">
<em>a low latency closed loop feedback system demonstrating communication the game of Pong with a Biological Neural Network</em></p>

<h2 id="scalability">Scalability</h2>

<p>While scaling an Artificial Neural Network (ANN) involves buying more GPUs and using more electricity, scaling a BNN involves growing more biological tissue and keeping it alive. They are highly scalable, and there is a clear energy advantage.</p>

<h3 id="the-energy-advantage">The Energy Advantage</h3>

<p>ANNs: As you add “neurons” to a digital model (like GPT-4), the energy cost explodes. Massive data centers are required.</p>

<p>BNNs: The human brain has 86 billion neurons but runs on only 20 watts (about the same as a dim lightbulb). Scaling a BNN from 800,000 to 80 million neurons doesn&#39;t require a power plant; it just requires a bit more “sugar water”.</p>

<h2 id="conclusion-the-dawn-of-the-bio-computer">Conclusion: The Dawn of the Bio-Computer</h2>

<p>The success of biological neural networks in mastering games like Pong and Doom is more than just a scientific curiosity; it is a <strong>proof of concept for a new era of Synthetic Biological Intelligence</strong>. We are moving away from simply trying to mimic the brain with code and toward <strong>partnering with it as a hardware component</strong>.</p>

<p>As digital AI models grow larger, their carbon footprint becomes a global concern. BNNs offer a path toward “Green AI,” where complex problem-solving requires <strong>milliwatts instead of megawatts</strong>. By leveraging the Free Energy Principle, we’ve seen that biology can adapt to new environments with a <strong>speed and flexibility that digital algorithms still struggle to match</strong>.</p>

<p>The story of Biological Neural Networks reminds us that while we have spent decades trying to make computers “smarter,” nature has already provided us with the <strong>most sophisticated, efficient, and adaptive processor in existence</strong>. The future of computing might not be found in bigger data centers, but in the incredibly fast world of the living cell.</p>

<h2 id="references">References</h2>
<ul><li>Kagan, B. J., Kitchen, A. C., Tran, N. T., Habibollahi, F., Khajehnejad, M., Parker, B. J., ... &amp; Friston, K. J. (2022). <a href="https://doi.org/10.1016/j.neuron.2022.09.001" rel="nofollow">In vitro neurons learn and exhibit sentience when embodied in a simulated game-world</a>. <em>Neuron</em>, 110(23), 3952-3969.</li></ul>

<hr>

<p><blockquote class="blockquote">
<p>“Writing is how I learn; sharing is how we grow.”
I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let&#39;s build something together.</p></blockquote>
Connect: 👥 <a href="https://www.linkedin.com/in/rani-giro/" rel="nofollow">Linkedin</a> ⭐ <a href="https://github.com/ImTheCurse" rel="nofollow">Github</a></p>
]]></content:encoded>
      <guid>https://blog.ranigiro.uk/dragonfly/when-analog-is-faster-than-digital-the-story-of-biological-neural-networks</guid>
      <pubDate>Mon, 09 Mar 2026 21:02:33 +0000</pubDate>
    </item>
    <item>
      <title>Stop digging through unreadable logs: A general guide to logging</title>
      <link>https://blog.ranigiro.uk/dragonfly/stop-digging-through-unreadable-logs-a-general-guide-to-logging</link>
      <description>&lt;![CDATA[By: Rani Giro&#xA;&#xA;an AI Generate Image&#xA;&#xA;Introduction&#xA;We’ve all been there: a production request fails, and you’re suddenly diving into a sea of disjointed log lines. You’re fishing for a trace here, a timestamp there, praying that you can manually stitch together the story of what actually happened.&#xA;&#xA;Let’s face it: Standard logging is an observability disaster. It’s hard to read, nearly impossible to debug quickly, and—worst of all—it’s incredibly expensive. Ingesting thousands of separate &#xA;!--more--&#xA;&#xA;What You’ll Learn in This Article&#xA;The &#34;Context Gap&#34; Problem: Why standard sequential logs make debugging in production a nightmare and how to fix it.&#xA;Request Aggregation: How to use Spring Boot’s @RequestScope to collect full request lifecycles into a single source of truth.&#xA;The Orchestration Layer: Implementing a Middleware to automatically capture metadata, durations, and exceptions without manual boilerplate.&#xA;Developer Experience: Using the RequestAwareService pattern to give your entire backend instant logging capabilities with zero dependency injection.&#xA;&#xA;Better Together - Aggregated Request Logging.&#xA;Instead of spraying lines everywhere, you collect everything into a single &#34;container&#34; during the request lifecycle. When the request finishes, you ship it as one comprehensive, structured JSON object.&#xA;&#xA;Implementation Example&#xA;The Orchestrator (LoggerMiddleware): This captures the start, the end, and any exceptions in between. This happens before each request that comes in.&#xA;&#xA;//LoggerMiddleware.java&#xA;@Slf4j&#xA;@Component&#xA;public class LoggerMiddleware extends OncePerRequestFilter{&#xA;&#xA;    @Autowired&#xA;    protected RequestLoggerService requestLogger;&#xA;&#xA;   @Override&#xA;    protected void doFilterInternal(&#xA;                                    @NonNull HttpServletRequest request, &#xA;                                    @NonNull HttpServletResponse response, &#xA;                                    @NonNull FilterChain filterChain&#xA;    ){ &#xA;&#xA;        // Before the request, we add request metadata.&#xA;        long startTime = System.currentTimeMillis();&#xA;        &#xA;        HashMapString,Object reqInfo = new HashMap();&#xA;        reqInfo.put(&#34;method&#34;, request.getMethod());&#xA;        reqInfo.put(&#34;path&#34;, request.getRequestURI());&#xA;        reqInfo.put(&#34;sessionid&#34;, request.getRequestedSessionId());&#xA;        reqInfo.put(&#34;protocol&#34;, request.getProtocol());&#xA;        reqInfo.put(&#34;issecure&#34;, request.isSecure());&#xA;        requestLogger.log(&#34;request&#34;, reqInfo);&#xA;&#xA;        try {&#xA;            // Call the request.&#xA;            filterChain.doFilter(request, response);&#xA;        }catch(Exception e){&#xA;            HashMapString,Object errorInfo = new HashMap();&#xA;            errorInfo.put(&#34;message&#34;,e.getMessage());&#xA;            errorInfo.put(&#34;cause&#34;, e.getCause());&#xA;            requestLogger.log(&#34;error&#34;, errorInfo);&#xA;        }finally {&#xA;            // After the request call finished.&#xA;            Object exception = request.getAttribute(&#34;jakarta.servlet.error.exception&#34;);&#xA;            if (exception instanceof Throwable) {&#xA;                HashMapString, Object errorDetails = new HashMap();&#xA;                errorDetails.put(&#34;message&#34;, ((Throwable) exception).getMessage());&#xA;                requestLogger.log(&#34;exception&#34;, errorDetails);&#xA;            }&#xA;            long duration = System.currentTimeMillis() - startTime;&#xA;&#xA;            HashMapString,Object respInfo = new HashMap();&#xA;            respInfo.put(&#34;requesttime_ms&#34;, duration);&#xA;            respInfo.put(&#34;status&#34;, response.getStatus());&#xA;            requestLogger.log(&#34;response&#34;, respInfo);&#xA;            requestLogger.publish();&#xA;        }&#xA;    } &#xA;&#xA;The Central Warehouse (LoggerService): This manages the data and handles the logging logic.&#xA;// LoggerService.java&#xA;@Slf4j&#xA;@Service&#xA;public class LoggerService {&#xA;    private final ObjectMapper objectMapper = new ObjectMapper();&#xA;    private static final ConcurrentHashMapString, ConcurrentHashMap&lt;String, Object  logs = new ConcurrentHashMap();&#xA;&#xA;    public void log(String requestId, String key, Object val) {&#xA;        // Insert the Request &#34;log&#34; into the log repositroy.&#xA;        logs.computeIfAbsent(requestId, id -  new ConcurrentHashMap())&#xA;                .put(key, val);&#xA;    }&#xA;&#xA;    public void publish(String requestURI, String requestId) {&#xA;        // Remove logs that are published.&#xA;        var requestLogs = logs.remove(requestId);&#xA;        if (requestLogs == null) {&#xA;            return;&#xA;        }&#xA;        try {&#xA;            // Actually log the object.&#xA;            log.info(objectMapper.writeValueAsString(requestLogs));&#xA;        } catch (Exception e) {&#xA;            log.error(&#34;Failed to publish logs&#34;, e);&#xA;        }&#xA;    }&#xA;&#xA;}&#xA;&#xA;The Request wrapper (RequestLoggerService): This calls the Logger service and automatically attaches the Request id so all aggregated data belong to the same request. This works concurrently. Notice we use the &#xA;//RequestLoggerService.java&#xA;@Component&#xA;@RequestScope&#xA;public class RequestLoggerService {&#xA;    private final String requestId;&#xA;    private final LoggerService logger;&#xA;    private final String requestURI;&#xA;&#xA;    public RequestLoggerService(HttpServletRequest request,LoggerService logger){&#xA;        this.requestId = request.getRequestId();&#xA;        this.logger = logger;&#xA;        this.requestURI = request.getRequestURI();&#xA;    }&#xA;&#xA;    public void log(String key, Object val){&#xA;        if(this.requestId == null){&#xA;            System.err.println(&#34;Failed to log, null request id.&#34;);&#xA;            return;&#xA;        }&#xA;        logger.log(this.requestId, key, val);&#xA;    }&#xA;&#xA;    public void publish(){&#xA;        if(this.requestId == null){&#xA;            System.err.println(&#34;Failed to log, null request id.&#34;);&#xA;            return;&#xA;        }&#xA;        logger.publish(this.requestURI,this.requestId);&#xA;    }&#xA;}&#xA;&#xA;Developer Experience (RequestAwareService): A simple base class that gives any business logic service instant access to the logger without the headache of manual Dependency Injection in every file. We can use the logger by doing &#xA;public abstract class RequestAwareService{&#xA;    @Autowired&#xA;    protected RequestLoggerService requestLogger;&#xA;}&#xA;Solving the Cost &amp; Noise Problem&#xA;There is a slight problem with this approach, storing detailed logs for every &#34;200 OK&#34; request is often a waste of money. We solve this by aggregating data into one object, you can implement Smart Sampling or Conditional Logging at the finish line.&#xA;&#xA;Final Thoughts&#xA;Moving from &#34;log-spraying&#34; to Contextual Aggregation is more than just a technical tweak, it’s a mindset shift from simple Logging to true Observability.&#xA;&#xA;By treating your logs as structured data objects rather than a stream of disjointed text, you gain:&#xA;&#xA;Speed: Debugging a production incident takes seconds when the entire context is in one JSON block.&#xA;Sanity: No more manual &#34;session ID&#34; stitching across thousands of lines.&#xA;Savings: You stop paying to store thousands of redundant log lines for healthy requests and focus your budget where it matters: the errors.&#xA;&#xA;If you are building high-scale applications, this pattern is a game-changer for both your developer experience and your infrastructure bill.&#xA;&#xA;---&#xD;&#xA;blockquote class=&#34;blockquote&#34;&#xD;&#xA;p&#34;Writing is how I learn; sharing is how we grow.&#34;&#xD;&#xA;I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let&#39;s build something together./p&#xD;&#xA;/blockquote&#xD;&#xA;Connect: 👥 Linkedin ⭐ Github&#xD;&#xA;&#xD;&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p><em>By: Rani Giro</em></p>

<p><img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/sGfLzceiasSHqxq?file=/&amp;fileId=21753&amp;x=2100&amp;y=1312&amp;a=true&amp;etag=6f9d9039f95147bf9f6ec8a0182d2e15" alt="an AI Generate Image"></p>

<h2 id="introduction">Introduction</h2>

<p>We’ve all been there: a production request fails, and you’re suddenly diving into a sea of disjointed log lines. You’re fishing for a trace here, a timestamp there, praying that you can manually stitch together the story of what actually happened.</p>

<p>Let’s face it: Standard logging is an observability disaster. It’s hard to read, nearly impossible to debug quickly, and—worst of all—it’s incredibly expensive. Ingesting thousands of separate <code>log.info</code> lines for every minor event burns through your cloud budget while providing very little signal.</p>



<h2 id="what-you-ll-learn-in-this-article">What You’ll Learn in This Article</h2>
<ul><li>The “Context Gap” Problem: Why standard sequential logs make debugging in production a nightmare and how to fix it.</li>
<li>Request Aggregation: How to use Spring Boot’s @RequestScope to collect full request lifecycles into a single source of truth.</li>
<li>The Orchestration Layer: Implementing a Middleware to automatically capture metadata, durations, and exceptions without manual boilerplate.</li>
<li>Developer Experience: Using the RequestAwareService pattern to give your entire backend instant logging capabilities with zero dependency injection.</li></ul>

<h2 id="better-together-aggregated-request-logging">Better Together – Aggregated Request Logging.</h2>

<p>Instead of spraying lines everywhere, you collect everything into a single “container” during the request lifecycle. When the request finishes, you ship it as one comprehensive, structured JSON object.</p>

<h2 id="implementation-example">Implementation Example</h2>

<p><strong>The Orchestrator (LoggerMiddleware)</strong>: This captures the start, the end, and any exceptions in between. This happens before each request that comes in.</p>

<pre><code class="language-java">//LoggerMiddleware.java
@Slf4j
@Component
public class LoggerMiddleware extends OncePerRequestFilter{

    @Autowired
    protected RequestLoggerService requestLogger;

   @Override
    protected void doFilterInternal(
                                    @NonNull HttpServletRequest request, 
                                    @NonNull HttpServletResponse response, 
                                    @NonNull FilterChain filterChain
    ){ 

        // Before the request, we add request metadata.
        long startTime = System.currentTimeMillis();
        
        HashMap&lt;String,Object&gt; reqInfo = new HashMap&lt;&gt;();
        reqInfo.put(&#34;method&#34;, request.getMethod());
        reqInfo.put(&#34;path&#34;, request.getRequestURI());
        reqInfo.put(&#34;session_id&#34;, request.getRequestedSessionId());
        reqInfo.put(&#34;protocol&#34;, request.getProtocol());
        reqInfo.put(&#34;is_secure&#34;, request.isSecure());
        requestLogger.log(&#34;request&#34;, reqInfo);

        try {
            // Call the request.
            filterChain.doFilter(request, response);
        }catch(Exception e){
            HashMap&lt;String,Object&gt; errorInfo = new HashMap&lt;&gt;();
            errorInfo.put(&#34;message&#34;,e.getMessage());
            errorInfo.put(&#34;cause&#34;, e.getCause());
            requestLogger.log(&#34;error&#34;, errorInfo);
        }finally {
            // After the request call finished.
            Object exception = request.getAttribute(&#34;jakarta.servlet.error.exception&#34;);
            if (exception instanceof Throwable) {
                HashMap&lt;String, Object&gt; errorDetails = new HashMap&lt;&gt;();
                errorDetails.put(&#34;message&#34;, ((Throwable) exception).getMessage());
                requestLogger.log(&#34;exception&#34;, errorDetails);
            }
            long duration = System.currentTimeMillis() - startTime;

            HashMap&lt;String,Object&gt; respInfo = new HashMap&lt;&gt;();
            respInfo.put(&#34;request_time_ms&#34;, duration);
            respInfo.put(&#34;status&#34;, response.getStatus());
            requestLogger.log(&#34;response&#34;, respInfo);
            requestLogger.publish();
        }
    } 
</code></pre>

<p><strong>The Central Warehouse (LoggerService):</strong> This manages the data and handles the logging logic.</p>

<pre><code class="language-java">// LoggerService.java
@Slf4j
@Service
public class LoggerService {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final ConcurrentHashMap&lt;String, ConcurrentHashMap&lt;String, Object&gt;&gt; logs = new ConcurrentHashMap&lt;&gt;();

    public void log(String requestId, String key, Object val) {
        // Insert the Request &#34;log&#34; into the log repositroy.
        logs.computeIfAbsent(requestId, id -&gt; new ConcurrentHashMap&lt;&gt;())
                .put(key, val);
    }

    public void publish(String requestURI, String requestId) {
        // Remove logs that are published.
        var requestLogs = logs.remove(requestId);
        if (requestLogs == null) {
            return;
        }
        try {
            // Actually log the object.
            log.info(objectMapper.writeValueAsString(requestLogs));
        } catch (Exception e) {
            log.error(&#34;Failed to publish logs&#34;, e);
        }
    }

}

</code></pre>

<p><strong>The Request wrapper (RequestLoggerService):</strong> This calls the Logger service and automatically attaches the Request id so all aggregated data belong to the same request. This works concurrently. Notice we use the <code>@RequestScope</code> annotation which is Spring Boot “magic”, that allows us to get the request context.</p>

<pre><code class="language-java">//RequestLoggerService.java
@Component
@RequestScope
public class RequestLoggerService {
    private final String requestId;
    private final LoggerService logger;
    private final String requestURI;

    public RequestLoggerService(HttpServletRequest request,LoggerService logger){
        this.requestId = request.getRequestId();
        this.logger = logger;
        this.requestURI = request.getRequestURI();
    }

    public void log(String key, Object val){
        if(this.requestId == null){
            System.err.println(&#34;Failed to log, null request id.&#34;);
            return;
        }
        logger.log(this.requestId, key, val);
    }

    public void publish(){
        if(this.requestId == null){
            System.err.println(&#34;Failed to log, null request id.&#34;);
            return;
        }
        logger.publish(this.requestURI,this.requestId);
    }
}
</code></pre>

<p><strong>Developer Experience (RequestAwareService):</strong> A simple base class that gives any business logic service instant access to the logger without the headache of manual Dependency Injection in every file. We can use the logger by doing <code>class SomeCustomClass extends RequestAwareService</code>.</p>

<pre><code class="language-java">public abstract class RequestAwareService{
    @Autowired
    protected RequestLoggerService requestLogger;
}
</code></pre>

<h2 id="solving-the-cost-noise-problem">Solving the Cost &amp; Noise Problem</h2>

<p>There is a slight problem with this approach, storing detailed logs for every “200 OK” request is often a waste of money. We solve this by aggregating data into one object, you can implement Smart Sampling or Conditional Logging at the finish line.</p>

<h2 id="final-thoughts">Final Thoughts</h2>

<p>Moving from “log-spraying” to Contextual Aggregation is more than just a technical tweak, it’s a mindset shift from simple Logging to true Observability.</p>

<p>By treating your logs as structured data objects rather than a stream of disjointed text, you gain:</p>
<ul><li>Speed: Debugging a production incident takes seconds when the entire context is in one JSON block.</li>
<li>Sanity: No more manual “session ID” stitching across thousands of lines.</li>
<li>Savings: You stop paying to store thousands of redundant log lines for healthy requests and focus your budget where it matters: the errors.</li></ul>

<p>If you are building high-scale applications, this pattern is a game-changer for both your developer experience and your infrastructure bill.</p>

<hr>

<p><blockquote class="blockquote">
<p>“Writing is how I learn; sharing is how we grow.”
I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let&#39;s build something together.</p></blockquote>
Connect: 👥 <a href="https://www.linkedin.com/in/rani-giro/" rel="nofollow">Linkedin</a> ⭐ <a href="https://github.com/ImTheCurse" rel="nofollow">Github</a></p>
]]></content:encoded>
      <guid>https://blog.ranigiro.uk/dragonfly/stop-digging-through-unreadable-logs-a-general-guide-to-logging</guid>
      <pubDate>Sat, 03 Jan 2026 15:53:14 +0000</pubDate>
    </item>
    <item>
      <title>Unlocking Creativity: How Diffusion Models Power Image and Video Generation</title>
      <link>https://blog.ranigiro.uk/dragonfly/unlocking-creativity-how-diffusion-models-power-image-and-video-generation</link>
      <description>&lt;![CDATA[By: Rani Giro&#xA;&#xA;An AI Generated Image&#xA;&#xA;Introduction&#xA;Artificial intelligence today feels almost magical. With a simple prompt, you can generate art in the style of Van Gogh using MidJourney or Stable Diffusion, create photorealistic images with DALL·E 3, bring old photos back to life with AI-powered restoration, and even generate 3D objects or video clips from text prompts.&#xA;&#xA;Behind these breakthroughs lies the same core technology: the diffusion model. While the name sounds abstract, the idea is both intuitive and fascinating once you peel back the layers.&#xA;&#xA;!--more--&#xA;&#xA;What You’ll Learn in This Article&#xA;How diffusion models differ from other AI systems&#xA;How diffusion models work&#xA;Why diffusion models never generate the same image twice&#xA;The role of compression and why it’s essential&#xA;Why the denoising process must happen step by step&#xA;Broader applications of diffusion beyond image generation&#xA;&#xA;---&#xA;How diffusion models work&#xA;Diffusion models work by gradually adding random noise to data (like an image) until it becomes pure noise, then training a neural network to reverse that process step by step. During generation, the model starts from random noise and denoises it iteratively, producing a new, coherent sample that matches the learned distribution. Because the denoising is stochastic (random), the same prompt never yields exactly the same output.&#xA;&#xA;Why Use Diffusion Models?&#xA;Generative AI has many approaches, but diffusion has emerged as one of the most powerful. Unlike GANs, which can be unstable to train, or auto-regressive models that can be slow and rigid, diffusion models offer a balance of stability, flexibility, and quality. They create outputs that feel fresh and original, and because they start from pure noise, no two results are identical. This makes them particularly suited to creativity-driven tasks, where uniqueness and variety are essential.&#xA;&#xA;Why Denoising Happens Step by Step&#xA;We have mentioned above that the process is iterative, lets use an analogy to understand why. Imagine you are lost in the middle of nowhere with a guide at your side. If the guide rattled off every instruction for the entire journey back home in one go, telling you to turn left here, walk five miles there, and cross three rivers, you would likely lose track halfway through and end up further away than where you started. But if the guide walked with you and gave you one clear instruction at a time, you would steadily find your way back with confidence.&#xA;&#xA;Diffusion model in latent space&#xA;Starting out with random noise, slowly finding our way back home.&#xA;We sample random noise from the normal distribution and slowly denoise our way to our desired representation.&#xA;Credit: Depth First, YouTube.&#xA;&#xA;That is essentially how diffusion works. The model does not try to leap from meaningless static to a polished image in one dramatic jump. Instead, it breaks the task into many smaller, manageable steps. At each stage, a little bit of noise is removed, and the image becomes slightly more coherent. Slowly, the structure emerges, details are refined, and the final picture comes into focus. This gradual refinement is what makes the results so reliable. Without these small steps, the model would easily get lost, producing chaotic or broken outputs. By moving patiently and predictably, diffusion ensures that the generated content feels both original and natural.&#xA;&#xA;Diffusion forwards and backwards pass&#xA;Diffusion training and inference process: we train the model to learn how to denoise our latent, “static” image in training and use the same model to infer our new image. &#xA;Credit: codoraven, “Diffusion Model Clearly Explained.”&#xA;&#xA;Beyond Just Images&#xA;While most people know diffusion through image generation, the same principles are spreading into many fields. In audio, it can generate music or entirely new synthetic voices. In video, researchers are building systems that can animate full clips from just a prompt. In 3D modeling, diffusion helps design assets for games and immersive environments. In medicine, it enhances MRI scans and even helps in molecule design. Diffusion is quickly becoming a foundation not only for creativity but also for innovation across industries.&#xA;&#xA;Final Thoughts&#xA;Diffusion models combine three powerful ideas: randomness to guarantee uniqueness, compression with VAE to make the process efficient, and step by step denoising to carefully refine the output. Together, they make a system that feels more like imagination than calculation.&#xA;&#xA;The next time you generate an image with MidJourney or restore a photo with AI, remember that it all began with noise. Step by step, the model transformed that chaos into something coherent and new. That patient process is what makes diffusion such a breakthrough in how machines create.&#xA;&#xA;---&#xD;&#xA;blockquote class=&#34;blockquote&#34;&#xD;&#xA;p&#34;Writing is how I learn; sharing is how we grow.&#34;&#xD;&#xA;I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let&#39;s build something together./p&#xD;&#xA;/blockquote&#xD;&#xA;Connect: 👥 Linkedin ⭐ Github&#xD;&#xA;&#xD;&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p><em>By: Rani Giro</em></p>

<p><img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/gMRqgZtXESaGTnJ?file=/&amp;fileId=20731&amp;x=1920&amp;y=1080&amp;a=true&amp;etag=51be000531be93e8b84a770145c84c59" alt="An AI Generated Image"></p>

<h2 id="introduction">Introduction</h2>

<p>Artificial intelligence today feels almost <strong>magical</strong>. With a simple prompt, you can generate art in the style of Van Gogh using MidJourney or Stable Diffusion, create photorealistic images with DALL·E 3, bring old photos back to life with AI-powered restoration, and even generate 3D objects or video clips from text prompts.</p>

<p>Behind these breakthroughs lies the same core technology: the <strong>diffusion model</strong>. While the name sounds abstract, the idea is both intuitive and fascinating once you peel back the layers.</p>



<h2 id="what-you-ll-learn-in-this-article">What You’ll Learn in This Article</h2>
<ul><li>How diffusion models differ from other AI systems</li>
<li>How diffusion models work</li>
<li>Why diffusion models never generate the same image twice</li>
<li>The role of compression and why it’s essential</li>
<li>Why the denoising process must happen step by step</li>
<li>Broader applications of diffusion beyond image generation</li></ul>

<hr>

<h2 id="how-diffusion-models-work">How diffusion models work</h2>

<p>Diffusion models work by gradually adding random noise to data (like an image) until it becomes pure noise, then training a neural network to reverse that process step by step. During generation, the model starts from random noise and denoises it iteratively, producing a new, coherent sample that matches the learned distribution. Because the denoising is stochastic (random), the same prompt never yields exactly the same output.</p>

<h2 id="why-use-diffusion-models">Why Use Diffusion Models?</h2>

<p>Generative AI has many approaches, but diffusion has emerged as one of the most powerful. Unlike GANs, which can be unstable to train, or auto-regressive models that can be slow and rigid, diffusion models offer a balance of stability, flexibility, and quality. They create outputs that feel <strong>fresh and original</strong>, and because they start from pure noise, no two results are identical. This makes them particularly suited to creativity-driven tasks, where uniqueness and variety are essential.</p>

<h2 id="why-denoising-happens-step-by-step">Why Denoising Happens Step by Step</h2>

<p>We have mentioned above that the process is iterative, lets use an analogy to understand why. Imagine you are lost in the middle of nowhere with a guide at your side. If the guide rattled off every instruction for the entire journey back home in one go, telling you to turn left here, walk five miles there, and cross three rivers, you would likely lose track halfway through and end up further away than where you started. But if the guide walked with you and gave you one clear instruction at a time, you would steadily find your way back with confidence.</p>

<p><img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/fmSQF6RBBLbKY62?file=/&amp;fileId=20721&amp;x=1920&amp;y=1080&amp;a=true&amp;etag=b17329473a05128f3ff2981f79a168e7" alt="Diffusion model in latent space">
<em>Starting out with random noise, slowly finding our way back home.
We sample random noise from the normal distribution and slowly denoise our way to our desired representation.
Credit: Depth First, YouTube.</em></p>

<p>That is essentially how diffusion works. The model does not try to leap from meaningless static to a polished image in one dramatic jump. Instead, it breaks the task into many smaller, manageable steps. At each stage, a little bit of noise is removed, and the image becomes slightly more coherent. Slowly, the structure emerges, details are refined, and the final picture comes into focus. This gradual refinement is what makes the results so reliable. Without these small steps, the model would easily get lost, producing chaotic or broken outputs. By moving patiently and predictably, diffusion ensures that the generated content feels both original and natural.</p>

<p><img src="https://cloud.ranigiro.uk/apps/files_sharing/publicpreview/yGLYby3KwzXyG9f?file=/&amp;fileId=20733&amp;x=1920&amp;y=1080&amp;a=true&amp;etag=1e1f03c96c463444eef6bbf6d902ab14" alt="Diffusion forwards and backwards pass">
<em>Diffusion training and inference process: we train the model to learn how to denoise our latent, “static” image in training and use the same model to infer our new image.
Credit: codoraven, “Diffusion Model Clearly Explained.”</em></p>

<h2 id="beyond-just-images">Beyond Just Images</h2>

<p>While most people know diffusion through image generation, the same principles are spreading into many fields. In <strong>audio</strong>, it can generate music or entirely new synthetic voices. In <strong>video</strong>, researchers are building systems that can animate full clips from just a prompt. In <strong>3D modeling</strong>, diffusion helps design assets for games and immersive environments. In <strong>medicine</strong>, it enhances MRI scans and even helps in molecule design. Diffusion is quickly becoming a foundation not only for creativity but also for innovation across industries.</p>

<h2 id="final-thoughts">Final Thoughts</h2>

<p>Diffusion models combine three powerful ideas: <strong>randomness</strong> to guarantee uniqueness, <strong>compression with VAE</strong> to make the process efficient, and <strong>step by step denoising</strong> to carefully refine the output. Together, they make a system that feels more like <strong>imagination</strong> than calculation.</p>

<p>The next time you generate an image with MidJourney or restore a photo with AI, remember that it all began with <strong>noise</strong>. Step by step, the model transformed that chaos into something coherent and new. That patient process is what makes diffusion such a breakthrough in how machines create.</p>

<hr>

<p><blockquote class="blockquote">
<p>“Writing is how I learn; sharing is how we grow.”
I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let&#39;s build something together.</p></blockquote>
Connect: 👥 <a href="https://www.linkedin.com/in/rani-giro/" rel="nofollow">Linkedin</a> ⭐ <a href="https://github.com/ImTheCurse" rel="nofollow">Github</a></p>
]]></content:encoded>
      <guid>https://blog.ranigiro.uk/dragonfly/unlocking-creativity-how-diffusion-models-power-image-and-video-generation</guid>
      <pubDate>Wed, 10 Sep 2025 17:42:00 +0000</pubDate>
    </item>
  </channel>
</rss>